我有这个枚举代码:
enum Duration { Day, Week, Month };
Run Code Online (Sandbox Code Playgroud)
我可以为此枚举添加扩展方法吗?
你们都这样做了:
public void Proc(object parameter)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
// Main code.
}
Run Code Online (Sandbox Code Playgroud)
Jon Skeet曾经提到他有时会使用扩展来进行检查,所以你可以这样做:
parameter.ThrowIfNull("parameter");
Run Code Online (Sandbox Code Playgroud)
所以我得到了这个扩展的两个实现,我不知道哪个是最好的.
第一:
internal static void ThrowIfNull<T>(this T o, string paramName) where T : class
{
if (o == null)
throw new ArgumentNullException(paramName);
}
Run Code Online (Sandbox Code Playgroud)
第二:
internal static void ThrowIfNull(this object o, string paramName)
{
if (o == null)
throw new ArgumentNullException(paramName);
}
Run Code Online (Sandbox Code Playgroud)
你怎么看?
/*I have defined Extension Methods for the TypeX like this*/
public static Int32 GetValueAsInt(this TypeX oValue)
{
return Int32.Parse(oValue.ToString());
}
public static Boolean GetValueAsBoolean(this TypeX oValue)
{
return Boolean.Parse(oValue.ToString());
}
TypeX x = new TypeX("1");
TypeX y = new TypeX("true");
//Method #1
Int32 iXValue = x.GetValueAsInt();
Boolean iYValue = y.GetValueAsBoolean();
//Method #2
Int32 iXValueDirect = Int32.Parse(x.ToString());
Boolean iYValueDirect = Boolean.Parse(y.ToString());
Run Code Online (Sandbox Code Playgroud)
不要被TypeX带走,说我应该在TypeX中定义那些方法而不是扩展)我无法控制它(实际类我定义它在SPListItem上.
我想将TypeX转换为Int或Boolean,这个操作是我在代码中的很多Places中做的一件常见的事情.我想知道这会导致性能下降.我试图使用Reflector解释IL代码,但我并不擅长.可能对于上面的例子,不会有任何性能降低.总的来说,我想知道在使用Extension方法时对Regard对Performance的影响.
可能重复:
扩展方法性能
在一个CPU和/或内存访问限制的数据处理应用程序中,一行扩展方法的开销是否显着?它是否比普通函数调用更高,还是仅仅是编译器/ IDE抽象?例如,如果以下函数每秒被调用数千次,那么它是否会被告知:
public static void WriteElementString(this XmlTextWriter writer, string name, int data)
{
writer.WriteElementString(name, data.ToString());
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
扩展方法性能
当我以任何方式使用扩展方法时,我会遇到性能问题吗?
举个例子:
假设我在类型字符串上有100个扩展方法,并且有一个具有50个字符串属性的业务对象.现在我创建了这个业务对象的集合,可能有500个项目?
字符串上的这些扩展方法对RAM,CPU,......有什么影响!
我真的很喜欢扩展方法,但我想知道它的用法是否存在限制.
是否有更优雅的解决方案将项目添加到IEnumerable而不是这个
myNewIEnumerable = myIEnumerable.Concat ( Enumerable.Repeat (item, 1) );
Run Code Online (Sandbox Code Playgroud)
?
一些背景:
public void printStrings (IEnumerable<string> myStrings) {
Console.WriteLine ("The beginning.");
foreach (var s in myStrings) Console.WriteLine (s);
Console.WriteLine ("The end.");
}
...
var result = someMethodDeliveringAnIEnumerableOfStrings ();
printStrings (result.Concat ( Enumerable.Repeat ("finished", 1) ) );
Run Code Online (Sandbox Code Playgroud)