0

Say that I have a webpage called myPage which implement Page, but also implement my own interface called myInterface. My objective is to call a function called myFunction in myInterface with just the name of the class in string.

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

Now here is what information I have available to me:

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

How do get from here to something along the line of:

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

EDIT: Here is when I try to create an instance of MyInterface and it does not work:

Type myTypeObj = Type.GetType("MyPage1");
MyInterface MyPage1_instance = (MyInterface) Activator.CreateInstance (myTypeObj);
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

1 Answers1

0

If you're looking for information that doesn't change from one instance of your type to the next, you should probably use an attribute. Here is an example:

[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"));
    }
}

A couple of notes

  • Look around in System.ComponentModel to see if there is already an appropriate attribute for what you're trying to do. I used the Description attribute for this example. If you can't find a good one, create your own custom attribute.
  • It would probably be better to use Type.GetType("Qualified.Name.Of.Page1") if you have that information available.
default.kramer
  • 5,943
  • 2
  • 32
  • 50