简体   繁体   中英

C# Generics Casting. Casting from Base Class

I have a C# viewmodel to which I'm passing a generic type in the constructor:

public ViewModelTestPage(IIncrementalLoadingHelper<MessageDTO> incrementalLoadingHelper)
    {
        IncrementalLoadingHelper = incrementalLoadingHelper;
    }

In my ViewModel base class I have the following property:

public IIncrementalLoadingHelper<BaseDTO> IncrementalLoadingHelper {get; set;}

MessageDTO inherits from BaseDTO .

On the line which sets IncrementalLoadingHelper = incrementalLoadingHelper , I'm getting an error:

Cannot implicitly convert type IIncrementalLoadingHelper<MessageDTO> to IIncrementalLoadingHelper<BaseDTO> . An explicit conversion exists (are you missing a cast?)

I probably am missing a cast, but I have no idea how to do this. Could someone point me in the right direction, please?

All you actually need is a generic out modifier on the generic type:

    class BaseDTO { }
    class MessageDTO : BaseDTO { }
    interface IIncrementalLoadingHelper<out T> { }

    class ViewModelTestPage
    {
        IIncrementalLoadingHelper<BaseDTO> IncrementalLoadingHelper { get; }

        public ViewModelTestPage(IIncrementalLoadingHelper<MessageDTO> incrementalLoadingHelper)
        {
            IncrementalLoadingHelper = incrementalLoadingHelper;
        }
    }

That said, it doesn't make much sense to me that the property is of the base type, but the constructor takes the derived type. Why not just use the derived type as the property type then?

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