문제

Imagine the Func Func<Arguments, bool?>, where Arguments is an abstract class. Somewhere, for some reason I create a list of these functions with all kind of derived classes as arguments. Of course the type of Arguments is important for validation before the Func is called. Is there a way to get the type of Arguments?

e.g.:

public bool? test(Arguments arg) {
    Func test    = Func<SomeArguments, bool?>;
    Type argType = GetFirstArgumentType(test); // gives SomeArguments.GetType();

    if (arg.GetType() == argType) {
        return test(new SomeArguments());
    }
    return null;
}
도움이 되었습니까?

해결책

You can use Type.GetGenericArguments to get the System.Type of the first generic argument to your Func<T,bool?>.

That being said, it would likely be easier to store a Dictionary<Type, Delegate> to hold your types, and just do a direct lookup instead.

다른 팁

Based on your description, " Somewhere, for some reason I create a list of these functions with all kind of derived classes as arguments. " I might suggest that you use a parameter constraint:

 public bool? test<T>(T arg)  where T :Arguments, new()
 { 
     var type = typeof(T);

     // ...              
 }

This will get you the type checking you describe.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top