【问题标题】:How do you make instance of Page implementation with just class name in string?你如何用字符串中的类名制作 Page 实现的实例?
【发布时间】:2012-05-31 19:54:03
【问题描述】:

假设我有一个名为 myPage 的网页,它实现了 Page,但也实现了我自己的名为 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);

【问题讨论】:

  • 你可能在这个问题背后有更多的东西......否则会是stackoverflow.com/questions/648160/…的重复
  • 好吧,我试过了,但没用,因为我认为它是部分课程。
  • 好的,它是重复的,我添加了命名空间,现在它可以工作了。

标签: c# asp.net


【解决方案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")

【讨论】:

  • 非常有趣...不知道有这样的东西存在。谢谢!
猜你喜欢
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多