Pav*_*rno 13 .net c# generics casting
我有以下泛型类
public class Home<T> where T : Class
{
public string GetClassType
{
get{ return T.ToString() }
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我得到一个对象X,我肯定知道它是Home:
public void DoSomething(object x)
{
if(x is // Check if Home<>)
{
// I want to invoke GetClassType method of x
// but I don't know his generic type
x as Home<?> // What should I use here?
}
}
Run Code Online (Sandbox Code Playgroud)
我是否可以在不指定类的泛型类型的情况下进行转换?
如果您确定参数DoSomething
将是a Home<T>
,为什么不将其作为通用方法?
public void DoSomething<T>(Home<T> home)
{
...
}
Run Code Online (Sandbox Code Playgroud)
当然,如果DoSomething
逻辑上应该是一个实例方法,那就更容易了Home<T>
.
如果你真的想坚持你拥有的东西,你可以使用反射(未经测试):
public void DoSomething(object x)
{
// null checks here.
Type t = x.GetType();
if (t.IsGenericType &&
&& t.GetGenericTypeDefinition() == typeof(Home<>))
{
string result = (string) t.GetProperty("GetClassType")
.GetValue(x, null);
Console.WriteLine(result);
}
else
{
... // do nothing / throw etc.
}
}
Run Code Online (Sandbox Code Playgroud)
如果Home从基类派生怎么办?
public class Home
{
public virtual string GetClassType { get; }
}
public class Home<T> : Home
where T : class
{
public override string GetClassType
{
get{ return T.ToString() }
}
...
}
Run Code Online (Sandbox Code Playgroud)
然后
public void DoSomething(object x)
{
if(x is Home)
{
string ct = ((Home)x).GetClassType;
...
}
}
Run Code Online (Sandbox Code Playgroud)