是否可以使用扩展方法扩展通用 class?
Is it possible to extend a generic class using extension methods?
我想构建一个可以应用于任何应用的通用扩展方法class,但我不确定该怎么做。
到目前为止我有:
public static class ClassExtensionMethods
{
public static string GetName(this class tempClass)
{
return typeof(tempClass).Name;
}
}
所以我可以将其用作:
var NameOfClass1 = MyClass.GetName();
var NameOfClass2 = DiffClass.GetName();
但目前无法编译。
是否可以这样做,或者我是否必须在 Type
上执行扩展方法?
您不能拥有静态扩展方法,而且我看不到任何解决方法来实现您想要的。
这有什么问题?
var nameOfClass1 = typeof(MyClass).Name;
还是太长了?没办法让它更短。
好的,将扩展名放在 Type
上,因为您无法扩展 class
。您只能扩展值,而不能扩展类型。
因此您的 Type
扩展方法将是:
public static string GetName(this Type type)
{
return type.Name;
}
你会像这样使用它:
typeof(MyClass).GetName();
只需使方法通用:
public static class ClassExtensionMethods
{
public static string GetName<T>(this T tempClass)
{
return typeof(T).Name;
}
}
这需要您在 T 的实例上调用该方法。
但是您的情况不是一个很好的例子,因为您可以直接在 Type 上调用 .Name
;不需要扩展方法。
如果你只想将 T 限制为 类,你可以添加 where T : class
:
public static string GetName<T>(this T tempClass) where T : class
{
return typeof(T).Name;
}
我想构建一个可以应用于任何应用的通用扩展方法class,但我不确定该怎么做。
到目前为止我有:
public static class ClassExtensionMethods
{
public static string GetName(this class tempClass)
{
return typeof(tempClass).Name;
}
}
所以我可以将其用作:
var NameOfClass1 = MyClass.GetName();
var NameOfClass2 = DiffClass.GetName();
但目前无法编译。
是否可以这样做,或者我是否必须在 Type
上执行扩展方法?
您不能拥有静态扩展方法,而且我看不到任何解决方法来实现您想要的。
这有什么问题?
var nameOfClass1 = typeof(MyClass).Name;
还是太长了?没办法让它更短。
好的,将扩展名放在 Type
上,因为您无法扩展 class
。您只能扩展值,而不能扩展类型。
因此您的 Type
扩展方法将是:
public static string GetName(this Type type)
{
return type.Name;
}
你会像这样使用它:
typeof(MyClass).GetName();
只需使方法通用:
public static class ClassExtensionMethods
{
public static string GetName<T>(this T tempClass)
{
return typeof(T).Name;
}
}
这需要您在 T 的实例上调用该方法。
但是您的情况不是一个很好的例子,因为您可以直接在 Type 上调用 .Name
;不需要扩展方法。
如果你只想将 T 限制为 类,你可以添加 where T : class
:
public static string GetName<T>(this T tempClass) where T : class
{
return typeof(T).Name;
}