简体   繁体   中英

Generic inheritance and type conversion

So I'm attempting to abstract some WPF View/View Models into decoupled reusable objects. And now I'm stuck in such a way that I'm not even sure what to try next. I am hoping someone out there can help get my brain unlocked.

Here is a simplified example and error

    public interface IBasicListDto{}

    public interface IBasicListVm<T> where T : IBasicListDto
    {
        void DoSomthing();
    }  

    public class BasicListVm<T> : IBasicListVm<T> where T : IBasicListDto
    {
        public void DoSomthing()
        {
            Console.WriteLine("woohoo!!");
        }
    }

   public class MyBasicListDto : IBasicListDto{}

   public class MyBasicListVm<T> : BasicListVm<T> where T : MyBasicListDto {}

   private void Button_Click(object sender, RoutedEventArgs e)
   {
        IBasicListVm<IBasicListDto> vm = (IBasicListVm<IBasicListDto>)new MyBasicListVm<MyBasicListDto>();
        vm.DoSomthing();
    }   

I get the following run-time error on the first line in Button_Click method.

System.InvalidCastException was unhandled HResult=-2147467262 Message=Unable to cast object of type 'MyBasicListVm 1[testGenericInheritance.MainWindow+MyBasicListDto]' to type 'IBasicListVm 1[testGenericInheritance.MainWindow+IBasicListDto]'. Source=testGenericInheritance StackTrace:

I have seen a few similar questions/answers, but my brain is just not "Getting it" enough to make needed changes.

You can make IBasicListVm<T> covariant:

public interface IBasicListVm<out T> where T : IBasicListDto
{
    void DoSomthing();
}

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