简体   繁体   中英

How to do something like “Class<? extends MyClass >” in C#

I need to use reflection in C# and i know it have a Type object that let you work with reflection like Java's Class do, but i need to specify a type or subtypes like the Java code below:

public class Test{

    class Test2 extends Test { }        

    public static void doSomething(Class<? extends Test> myClass){
        //doSomething with class...
    }

    public static void main(String[] args){
        doSomething(Test2.class); //ok
        doSomething(String.class); //error
    }

}

In the .NET framework, Type isn't generic. There's only one type Type. You can't specific that you only want a Type that describes a type derived from a given type, at least not statically.

You can of course do

public class Test
{
    public void DoSomething(Type myClass)
    {
        if(!typeof(Test).IsAssignableFrom(myClass))
        {
            throw new ArgumentException("myClass must refer to Test or a derived class", "myClass");
        }
    }
}

Maybe you want constraints on type parameters?

public class Student<T> where T : Person

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

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