6

Microsoft Unityを利用するフレームワークにカスタムビジネスロジックを挿入するために、インターフェイスを実装しています。私の主な問題は、実装する必要のあるインターフェイスが次のメソッドを定義していることです。

T InterfaceMethod<T>();

T制約はありません。私のコードでは、別のサードパーティライブラリからメソッドを呼び出す必要があります。メソッドシグネチャは次のとおりです。

T AnotherMethod<T>() where T: class;

タイプTは、のロジックにとって重要ですAnotherMethodAnotherMethod<T>()リフレクションを使用せずに、実装内で呼び出す方法はありますか?Tが値型の場合は、明らかに別のアクションを実行する必要があります。これを回避するためにオートボックス化する方法はおそらくありますか?

4

3 に答える 3

2

これが正確に必要なものかどうかはわかりませんが、これにより、リフレクションを使用せずにInterfaceMethodからAnotherMethodを呼び出すことができます。ただし、Convert.ChangeTypeは引き続き使用されます。

アイデアは、クラスの実装を制約付きのジェネリックにすることです(ここではTin)。次に、InterfaceMethodの制約のないタイプTをTinに変換します。最後に、制約付きタイプを使用してAnotherMethodを呼び出すことができます。以下は文字列で正常に機能します。

public interface ITest
{
    T InterfaceMethod<T> (T arg);
}

public interface ITest2
{
    U AnotherMethod<U>(U arg) where U : class;
}

public class Test<Tin> : ITest, ITest2 where Tin : class
{
    public T InterfaceMethod<T> (T arg)
    {
        Tin argU = arg as Tin;
        if (argU != null)
        {
            Tin resultU = AnotherMethod(argU);
            T resultT = (T)Convert.ChangeType(resultU,typeof(T));
            return resultT;
        }
        return default(T);
    }

    public U AnotherMethod<U> (U arg) where U : class { return arg; }
}
于 2012-07-25T18:44:11.093 に答える
1

あなたが探していることは、反省なしに可能だとは思いません。AnotherMethod<object>()せいぜい、結果を呼び出してキャストするだけです。AnotherMethodしかし、これは、 'sTがあなたの目的にとって重要でない場合にのみ実際に正しく機能します。

于 2012-07-25T02:28:24.983 に答える
0

他の人が言っていることは、あなたはこのようなオブジェクトを通り抜けることができるということです:

public interface ITest
{
    T InterfaceMethod<T>(T arg);
}

public interface IAnotherTest
{
    U AnotherMethod<U>(U arg) where U : class;
}

public class Test : ITest
{
    private IAnotherTest _ianothertest;

    public T InterfaceMethod<T>(T arg)
    {
        object argU = arg as object;
        if (argU != null)
        {
            object resultU = _ianothertest.AnotherMethod(argU);
            T resultT = (T)Convert.ChangeType(resultU, typeof(T));
            return resultT;
        }
        return default(T);
    }
}
于 2012-07-26T17:44:58.070 に答える