2012-09-13 30 views
1

我有一些从接口派生的类,我希望能够检查代码,看看传​​入的对象是否从该接口派生,但我不知道确切的方法调用...如何检查对象是否从接口派生?

interface file 
{ 
} 

class createFile : file 
{ 
    string name; 
} 

class deleteFile : file 
{ 
    string name; 
} 

// Input here can be a string or a file 
void operateOnFileString(object obj) 
{ 
    Type type = obj.GetType(); 

    // Trying to avoid this ... 
    // if(type is createFile || type is deleteFile) 

    // I dont know exactly what to check for here 
    if(type is file) // its not, its 'createFile', or 'deleteFile' 
    { 
     print("Its a file Type"); 
    } 
    else 
     print("Error: Its NOT a file Type"); 
} 

实际上我已经从该接口数百派生类的,我想,以避免检查每一种类型,并具有当我创建该类型另一个类添加的检查。

+1

.Net类型名称应该是UpperCamelCase,并且接口应该以'I'开始。 – SLaks

+0

您的编码约定很糟糕,真的会降低您的代码的可读性。如果您希望其他人阅读您的代码并回答问题,我建议您多付出一些努力。 – ProfK

回答

7

is是完全正确的。
但是,您需要检查实例本身。

obj.GetType()返回描述对象实际类的System.Type类的实例。你可以写if (obj is IFile)

+1

Tizz,SLaks在这里是正确的。我也建议不要传入'obj'作为对象。如果你传入一个'文件',任何调用都将被强制传入一个实现'文件'的对象。另外,要小心你的命名约定和套管。在C#中,我们更喜欢使用以I开头的接口,所以在这种情况下使用IFile。 –

1

你可以使用BaseType

if (type.BaseType is file) 

由于file是一个接口,使用Type.GetInterfaces检查的type底层接口:

if (type.GetInterfaces().Any(i => i.Equals(typeof(file)) 

或者可能有点更快, 使用Type.GetInterface

if (type.GetInterface(typeof(file).FullName) != null) 

(该搜索的type和继承的类或接口的接口。)

+0

不;这将无法正常工作。 – SLaks

+2

'IsAssignableFrom()' – SLaks

3

您传递错误的参数is。正确的是

if (obj is file) { 
    // ... 
} 

但是,如果你有直接接受file参数方法的重载它甚至会更好。事实上,目前还不清楚如何接受object可以有效地使用它。

2
If(yourObject is InterfaceTest) 
{ 
    return true; 
} 
2
  1. is运营商的工作,或者你可以这样做:

    if (someInstance is IExampleInterface) { ... } 
    
  2. if(typeof(IExampleInterface).IsAssignableFrom(type)) { 
    ... 
    } 
    
0

你可以创建像下面

扩展方法
/// <summary> 
    /// Return true if two types or equal, or this type inherits from (or implements) the specified Type. 
    /// Necessary since Type.IsSubclassOf returns false if they're the same type. 
    /// </summary> 
    public static bool IsSameOrSubclassOf(this Type t, Type other) 
    { 
     if (t == other) 
     { 
      return true; 
     } 
     if (other.IsInterface) 
     { 
      return t.GetInterface(other.Name) != null; 
     } 
     return t.IsSubclassOf(other); 
    } 

    and use it like below 

    Type t = typeof(derivedFileType); 
    if(t.IsSameOrSubclassOf(typeof(file))) 
    { } 
+0

我不确定你为什么要这么做 –

相关问题