我有一组扩展方法,我经常用于各种UI任务.我通常将它们定义为运行类型object,即使在它们内部我通常将它们转换为字符串类型.
public static string FormatSomething(this object o)
{
if( o != null )
{
string s = o.ToString();
/// do the work and return something.
}
// return something else or empty string.
}
Run Code Online (Sandbox Code Playgroud)
我使用类型object而不是使用类型的主要原因string是<%#Eval("Phone").ToString().FormatSomething()%>在我可以做的时候将自己保存在UI中<%#Eval("Phone").FormatSomething()%>.
那么,从性能的角度来看,创建所有扩展方法是否正常object,或者我应该根据扩展方法的作用将它们转换为string(或相关)类型?
/*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的影响.