Cast to generic type in C#

前端 未结 13 899
野性不改
野性不改 2021-01-30 20:27

I have a Dictionary to map a certain type to a certain generic object for that type. For example:

typeof(LoginMessage) maps to MessageProcessor

        
13条回答
  •  孤城傲影
    2021-01-30 21:17

    I had a similar problem. I have a class;

    Action
    

    which has a property of type T.

    How do I get the property when I don't know T? I can't cast to Action<> unless I know T.

    SOLUTION:

    Implement a non-generic interface;

    public interface IGetGenericTypeInstance
    {
        object GenericTypeInstance();
    }
    

    Now I can cast the object to IGetGenericTypeInstance and GenericTypeInstance will return the property as type object.

提交回复
热议问题