2009-06-11 17 views
3

次のコードはちょうど作成されていますが、これはC#で可能ですか?ジェネリッククラスのメソッドとは異なる戻り値の型

class A 
{ 
    public int DoStuff() 
    { 
     return 0; 
    } 
} 

class B 
{ 
    public string DoStuff() 
    { 
     return ""; 
    } 
} 

class MyMagicGenericContainer<T> where T : A, B 
{ 
    //Below is the magic <------------------------------------------------ 
    automaticlyDetectedReturnTypeOfEitherAOrB GetStuff(T theObject) 
    { 
     return theObject.DoStuff(); 
    } 
} 

答えて

6

あなたの願いは私のコマンドです (申し訳ありませんが、私は構文を検証するために開いVisStudioを持っていないか、それが正しい動作すること):

別のオプションは、このような何かを行うことです。

public class MyMagicContainer<U> 
{ 
    U GetStuff(Func<U> theFunc) 
    { 
    return theFunc() 
    } 
} 
+0

ありがとう:あなたは以下のカップリングをしたい場合は

public interface IDoesStuff<T> { T DoStuff(); } public class A : IDoesStuff<int> { public int DoStuff() { return 0; } } public class B : IDoesStuff<string> { public string DoStuff() { return ""; } } public class MyMagicContainer<T, U> where T : IDoesStuff<U> { U GetStuff(T theObject) { return theObject.DoStuff(); } } 

、あなたが行くことができます。ちょっと冗長ですが、仕事は終わりです。 :) –

+0

私はTの意味を知っていますが、Uはどこから来たのですか?そのことについて私が知らない他の手紙がありますか? – jasonh

+1

jasonh、ジェネリックはどんな文字でも構いません –

2

automaticlyDetectedReturnTypeOfEitherAOrB()を呼び出して終了するメソッドは、戻り値の型を知る必要があります。メソッドがオブジェクトを返さない限り次に、呼び出し元のメソッドは何か(intまたはstring)を取り戻し、それをどうするかを把握できます。

R GetStuff<R>(T theObject) 
{ 
    return (R)theObject.DoStuff(); 
} 

void Method1() 
{ 
    int i = GetStuff<int>(new A()); 
    string s = GetStuff<string>(new B()); 
} 
関連する問題