开发者

Determine if object is any Predicate<T>

开发者 https://www.devze.com 2022-12-20 20:47 出处:网络
I\'ve got an IList<Delegate> that contains some Func<bool>s and some Predicate<T>s, where T varies. I later need to sort out which of these items are Predicate<T>s, but don\'t

I've got an IList<Delegate> that contains some Func<bool>s and some Predicate<T>s, where T varies. I later need to sort out which of these items are Predicate<T>s, but don't want to close the door to adding other Delegate types to the list later, so I do not want to do this by identifying objects by !(current_delegate is Func<bool>).

The highest abstraction below Predicate<T> is MulticastDelegate, which seems unhelpful (would need a non-generic Predicate type under Predicate<T>), and identifying the presence of the generic parameter is also useless given the other generic Delegates that may be present in the list.

The only other thing I've considered is checking the Name of the Type. To me, string comparison is a near-smell, but maybe that is the 开发者_如何学运维is the best and/or only way -- you tell me.

What is the best way to definitively determine that an object is any Predicate<T> without knowing the type of T?


Like this:

obj.GetType().GetGenericTypeDefinition() == typeof(Predicate<>)


Predicate<int> pred = ...;
var isPreidcate = pred.GetType().GetGenericTypeDefinition() == typeof(Predicate<>);

On another note, if you have a generic list, you shoulnd't need to check the types in it. You may want to rethink your design if you need to check for specific types within a list.


You can have a list of special classes which wrap your delegates and provide additional sorting information. So you'll indirectly solve the problem.


This should work well enough:

public static bool IsPredicate(object obj) {
    var ty = obj.GetType();
    var invoke = ty.GetMethod("Invoke");
    return invoke != null && invoke.ReturnType == typeof(bool);
}

The trick will be when you actually want to call the function, you will need to use reflection.

Here are some tests:

Func<bool> is pred? True
Func<int, bool> is pred? True
Predicate<int> is pred? True
Func<int> is pred? False 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号