转换没有特定类型的泛型类

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)

我是否可以在不指定类的泛型类型的情况下进行转换?

Ani*_*Ani 9

如果您确定参数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)


n8w*_*wrl 5

如果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)

  • 太棒了!我有一个具有 2 个属性的通用类:“SomeClass Query”和“List&lt;T&gt; Items”。我不关心“Items”,只需要“Query”,因此将其移至基类修复了它! (2认同)