简体   繁体   English

返回特定接口的类型?

[英]Return a Type of a specific interface?

Suppose there's a interface IView where several implementations exist. 假设有一个IView接口,其中存在多个实现。
Now there are multiple other classes that has the following property: 现在,还有其他多个具有以下属性的类:

public Type ViewType { get; }

I want to ensure that the returned Type is of type IView . 我想确保返回的Type是IView类型。
Is there any way to achieve this? 有什么办法可以做到这一点? (like where returnvalue: IView ) (例如where returnvalue: IView

Please note that the property does not return a instance of IView . 请注意,属性返回的实例IView
If so there would be this way: 如果是这样,将有这种方式:
public T GetView<T>() where T: IView { }

The other way would be to check the returned type at any place where the property is called - but that's a lot of code for the same check. 另一种方法是在调用该属性的任何位置检查返回的类型-但这需要很多代码才能进行相同的检查。

Both your solutions immediately sprang to mind. 您的两种解决方案立即浮现在脑海。

Perhaps you could alleviate the repetition of checking the returned type by adding a helper method: 也许您可以通过添加一个辅助方法来减轻检查返回类型的重复:

public bool ViewImplementsIView()
{
    return typeof(this.ViewType).GetInterfaces().Contains(typeof(IView));
}

That encapsulates the test into your class so you've reduced the amount of validation needed elsewhere - potentially, you could even throw an exception on your getter if this returns false. 它将测试封装到您的类中,因此您减少了其他地方所需的验证量-潜在地,如果此方法返回false,甚至可能在getter上引发异常。

try in this way 以这种方式尝试

bool ImplementsIView(object t)
{
   return typeof(IView).IsAssignableFrom(typeof(t.GetType()));
}

update 更新

 bool ImplementsIView(Type t)
    {
       return typeof(IView).IsAssignableFrom(typeof(t));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM