0

Page を実装する myPage という Web ページがあるとしますが、myInterface という独自のインターフェイスも実装しています。私の目的は、文字列内のクラスの名前だけで myInterface の myFunction という関数を呼び出すことです。

public interface MyInterfac{
          Myfunction();
    }
public partial class MyPage1: Page, MyInterface{ 
          Myfunction(){ return "AAA"; }
    }
public partial class MyPage2: Page, MyInterface{ 
          Myfunction(){ return "BBB"; }
    }

ここに私が利用できる情報があります:

    string pageName1 = "MyPage1";
    string pageName2 = "MyPage2";

ここから次の行に沿って何かに到達するにはどうすればよいですか:

   (MyInterface)MyPage1_instance.Myfunction();         //Should return AAA;
   (MyInterface)MyPage2_instance.Myfunction();         //Should return BBB;

編集: これは、MyInterface のインスタンスを作成しようとしたときに機能しない場合です。

Type myTypeObj = Type.GetType("MyPage1");
MyInterface MyPage1_instance = (MyInterface) Activator.CreateInstance (myTypeObj);
4

1 に答える 1

0

タイプの 1 つのインスタンスから次のインスタンスまで変わらない情報を探している場合は、おそらく属性を使用する必要があります。以下に例を示します。

[System.ComponentModel.Description("aaa")]
class Page1 { }

[System.ComponentModel.Description("bbb")]
class Page2 { }

[TestClass]
public class Tests
{
    private static string GetDescription(string typeName)
    {
        var type = System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes().Single(t => t.Name == typeName);

        return type.GetCustomAttributes(false)
            .OfType<System.ComponentModel.DescriptionAttribute>()
            .Single().Description;
    }

    [TestMethod]
    public void MyTestMethod()
    {
        Assert.AreEqual("aaa", GetDescription("Page1"));
        Assert.AreEqual("bbb", GetDescription("Page2"));
    }
}

いくつかのメモ

  • あなたSystem.ComponentModelがやろうとしていることに対して適切な属性がすでにあるかどうかを調べてください。Descriptionこの例では属性を使用しました。適切な属性が見つからない場合は、独自のカスタム属性を作成してください。
  • Type.GetType("Qualified.Name.Of.Page1")そういう情報があれば使ったほうがいいかもしれません。
于 2012-05-31T20:19:19.770 に答える