本文介绍了检查如果一个对象满足泛型参数约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似如下的界面:

public interface IInterface<T>
    where T : IInterface<T>
{
}



而现在我需要创建表示此接口的类型使用反射,如:

And now I need to create a type representing this interface using reflection, e.g.

typeof(IInterface<>).MakeGenericType(someType);



不过,我真的不知道会是什么类型的'SOMETYPE,直到运行时,它是可能的该类型将不会作为通用接口的类型参数有效,因此MakeGenericType失败。

However, I don't actually know what type 'someType' will be until runtime, and it's possible that the type won't be valid as a type argument for the generic interface, so MakeGenericType fails.

现在的问题是,我怎么能检查'SOMETYPE'是有效的对于通用约束?

The question is, how can I check that 'someType' is valid for the generic constraint?

推荐答案

说实话,在简单的办法是只需要调用 MakeGenericType ,赶上的ArgumentException 将被抛出,如果任何类型的说法是错误的(或者,如果你打错了类型参数)。

To be honest, the simplest approach would be to just call MakeGenericType and catch the ArgumentException that will be thrown if any type argument is wrong (or if you've got the wrong number of type parameters).

虽然你的可能的使用的以找到约束然后制定出他们每个人的手段,这将是丑陋和容易出错的代码。

While you could use Type.GetGenericParameterConstraints to find the constraints and then work out what each of them means, it's going to be ugly and bug-prone code.

我不知道的一般的类似提示只是尝试和catch,但在这种情况下,我认为这是怎么回事是最可靠的方法。否则,你只是重新实现支票在CLR将要执行反正 - ,什么是你完美的重新实现他们的机会? :)

I don't usually like suggesting "just try it and catch" but in this case I think it's going to be the most reliable approach. Otherwise you're just reimplementing the checks that the CLR is going to perform anyway - and what are the chances you'll reimplement them perfectly? :)

这篇关于检查如果一个对象满足泛型参数约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:16