我想测试一个类型是否实现了一组接口之一.
ViewData["IsInTheSet"] =
model.ImplementsAny<IInterface1, IInterface2, IInterface3, IInterface4>();
Run Code Online (Sandbox Code Playgroud)
我编写了以下扩展方法来处理这个问题.
是否有更可扩展的方式来编写以下代码?我仍然不想在利用泛型的同时编写新方法.
public static bool Implements<T>(this object obj)
{
Check.Argument.IsNotNull(obj, "obj");
return (obj is T);
}
public static bool ImplementsAny<T>(this object obj)
{
return obj.Implements<T>();
}
public static bool ImplementsAny<T,V>(this object obj)
{
if (Implements<T>(obj))
return true;
if (Implements<V>(obj))
return true;
return false;
}
public static bool ImplementsAny<T,V,W>(this object obj)
{
if (Implements<T>(obj))
return true;
if (Implements<V>(obj))
return true;
if (Implements<W>(obj))
return true;
return false;
}
public static bool ImplementsAny<T, V, W, X>(this object obj)
{
if (Implements<T>(obj))
return true;
if (Implements<V>(obj))
return true;
if (Implements<W>(obj))
return true;
if (Implements<X>(obj))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
为什么不使用以下内容:
public static bool ImplementsAny(this object obj, params Type[] types)
{
foreach(var type in types)
{
if(type.IsAssignableFrom(obj.GetType())
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样称呼它:
model.ImplementsAny(typeof(IInterface1),
typeof(IInterface2),
typeof(IInterface3),
typeof(IInterface4));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
480 次 |
| 最近记录: |