简体   繁体   中英

Cast generic with base type

I have the following class:

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


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

Somewhere in the code I am trying to cast given view model as a object to concrete generic type. Here what I am doing:

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 

}

Why cannot I cast that into ViewModel if viewModelAsObject variable is that class and TData is SomeClass type?

I tried to make a general example from your shown code:

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> { }

This example works fine, I guess there must be an error in your function ViewModelAsObject().

Otherwise please try to map your code to this example or create a Minimal, Complete, and Verifiable example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM