简体   繁体   中英

How to find out if a class is an instance of a generic interface in C#?

So is it possible to get an instance of Property<T> is Property and, not knowing its generic T type parameter, to call its methods?

private interface Property<T> 
{
    T Value { get;}
    void DestroyEarth();
}

class MyProperty : Property<int>
{
    public int Value{ get { return 1 }; }
    public void  DestroyEarth() { }
}

So I am wondering if I can call DestroyEarth() on MyProperty instances received by a method like

void PropertyCaller(Property p){p.DestroyEarth();}

(Note: we do not define or have simple Property class or interface nowhere )

Edit:

with the question edit, I would say: declare a non-generic interface and move the methods that don't relate to T , for example:

interface IProperty {
    object Value { get;}
    void DestroyEarth();
}
interface IProperty<T> : IProperty {
    new T Value { get;}
}

class MyProperty : IProperty<int>
{
    object IProperty.Value { get { return Value; } }
    public int Value{get {return 1;} }
    public void  DestroyEarth(){}
}

and just code against IProperty when you don't know the T .

(a different answer, from before you posted code, is in the history , for reference)

Then you have:

void PropertyCaller(IProperty p) { p.DestroyEarth(); }

Of course, you could also just let the compiler figure out the T :

void PropertyCaller<T>(IProperty<T> p) { p.DestroyEarth(); }

What are you asking for is an automatic conversion between Property<T> types to Property<object> (i guess) in cases where you don't know the T and still want to call that instance in some way. This can't be done for various reasons (research "covariance/contravariance" in generic types for some insight on the problem space).

I recommend doing this conversion yourself and implement an IProperty (non generic - see Marc's answer) interface on top of your Property<T> class that has the same signature but with T written as object. Then implement by hand the call re-directions to the T methods with casts when needed.

无论T为何,您的Property类都应具有一些实现,而Property<T>Property派生的,更多实现与T有关。

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