2

インターフェイスから派生したいくつかのクラスがあり、コードをチェックインして、渡されたオブジェクトがそのインターフェイスから派生したものかどうかを確認できるようにしたいのですが、メソッド呼び出しが正確にわからない...

interface IFile
{
}

class CreateFile : IFile
{
    string filename;
}

class DeleteFile : IFile
{
    string filename;
}

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

    // Trying to avoid this ...
    // if(theType is CreateFile || theType is DeleteFile)

    // I dont know exactly what to check for here
    if( theType is IFile ) // its not, its 'CreateFile', or 'DeleteFile'
        print("Its an IFile interface");
    else
        print("Error: Its NOT a IFile interface");
}

実際には、そのインターフェイスから何百もの派生クラスがあり、各タイプをチェックする必要がないようにし、そのタイプから別のクラスを作成するときにチェックを追加する必要がないようにしています。

4

6 に答える 6

8

is正確に正しいです。
ただし、インスタンス自体を確認する必要があります。

obj.GetType()System.Typeオブジェクトの実際のクラスを記述するクラスのインスタンスを返します。

あなたはただ書くことができますif (obj is IFile)

于 2012-09-13T19:14:22.497 に答える
6
  1. isオペレーターが機能するか、次のことができます。

    if (someInstance is IExampleInterface) { ... }
    
  2. また

    if(typeof(IExampleInterface).IsAssignableFrom(type)) {
     ...
    }
    
于 2012-09-13T19:17:17.433 に答える
3

に間違った引数を渡していますis。正しいのは

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

fileただし、パラメーターを直接受け取るメソッドのオーバーロードがあればさらに良いでしょう。実際、 を受け入れる人がそれをobject効率的に使用する方法はまったく不明です。

于 2012-09-13T19:15:05.873 に答える
2

使用できます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(これにより、継承されたクラスまたはインターフェイスのインターフェイスが検索されます。)

于 2012-09-13T19:14:54.070 に答える
2
If( yourObject is InterfaceTest)
{
   return true;
}
于 2012-09-13T19:15:20.510 に答える
1

以下のような拡張メソッドを作成できます

    /// <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)))
    { }
于 2012-09-13T19:17:24.210 に答える