使用基本类型转换通用

时间:2018-09-07 11:10:43

标签: c# generics casting

我有以下课程:

public abstract class ViewModel<TNavigationData> : BindableBase
        where TNavigationData : class, new()
{
   //....
}


   public class SomeClass()
   {
      public SomeClass()
      {
      }
   }

在代码的某个地方,我试图将给定的视图模型转换为具体泛型的对象。这是我在做什么:

protected virtual async Task NavigateImplAsync<TData>(IView view, TData navigationData)
            where TData : class, new()
{
     object viewModelAsObject = GetFromSomewhere() //this is ViewModel<SomeClass>

     //typeof(TData) = SomeClass

     var t4 = viewModelAsObject  as ViewModel<TData>;

     //this cast returns null however TData 

}

如果viewModelAsObject变量是该类,而TData是SomeClass类型,为什么不能将其转换为ViewModel?

1 个答案:

答案 0 :(得分:0)

我试图用您显示的代码作为一个通用示例:

static void Main(string[] args)
{
    SomeFunc<SomeClass>();
}

private static void SomeFunc<TData>() where TData : class, new()
{
    object gsc = IReturnSomeGenericClassWithSomeClass();

    var check = gsc as GenericClass<TData>;
    System.Console.WriteLine(check == null ? "is null" : "is not null");
}

private static GenericClass<SomeClass> IReturnSomeGenericClassWithSomeClass() { return new GenericClass<SomeClass>(); }

class SomeClass { }
class GenericClass<T> { }

此示例工作正常,我想您的函数ViewModelAsObject()中肯定有错误。

否则,请尝试将您的代码映射到此示例或create a Minimal, Complete, and Verifiable example