C#, WinForms and Extension Methods
The Question
Aside from all the obvious answers, what would cause extension methods to generate compiler errors like this one:
'DataType' does not contain a definition for 'YourExtensionMethodName'
I've got a real stumper here, and it's spelled out for you in detail below. I've exhausted all the possible causes I can think of.
Scenario
String
, in this case). StringExtensions.
, Intellisense appears as normal, with all of my extension methods listed. The Code (Or an Excerpt Thereof)
(Yep, this is the offending code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Roswell.Framework
{
public static class StringBuilderExtensions
{
public static string ToSentenceCase(this string value)
{
return value.Substring(0, 1).ToUpper() + value.Substring(1).ToLower();
}
public static string ToTitleCase(this string value)
{
string[] parts = value.Split(new string[] {" "}, StringSplitOptions.None);
System.Text.StringBuilder builder = new System.Text.StringBuilder();
foreach (string part in parts)
{
builder.Append(part.ToSentenceCase());
builder.Append(" ");
}
return builder.ToString();
}
}
}
And this is the code that consumes it:
using Roswell.Framework;
namespace Roswell.Windows.Command
{
/// <summary>
/// Views the SQL for an object in the database window.
/// </summary>
internal class ViewObjectDdlCommand
: MainWindowCommand
{
public override void Execute()
{
// ...
OpenCodeWindow(
string.Format("{0} - {1} - {2}",
dsn.Name,
objectName,
info.ToTitleCase()),
schemaItemType,
objectName);
}
}
}
From your code snippet, I can see you're calling ToTitleCase
on something called info
. But I can't see the type of that variable, which is the thing that will determine what is happening here.
Obviously it needs to be a string (if string was not a sealed class it could be something derived from string, but that's impossible for a sealed class).
So the only thing that makes sense (aside from a very unlikely compiler error) is that info
is not a string.
The error suggests the answer:
'DataType' does not contain a definition for 'YourExtensionMethodName'
In this case, my guess is that "info" ( ViewObjectDdlCommand.info
) is not a string, but rather DataType. Try changing it to:
OpenCodeWindow(
string.Format("{0} - {1} - {2}",
dsn.Name,
objectName,
info.ToString().ToTitleCase()),
schemaItemType,
objectName);
链接地址: http://www.djcxy.com/p/96946.html
上一篇: 泛型通用扩展方法(原文如此!)
下一篇: C#,WinForms和扩展方法