这是你遇到的问题吗?
public void Demo()
{
var myInstance = Activator.CreateInstance((new Person()).GetType());
Console.WriteLine(Test(myInstance));
}
private string Test(object x) //this is the method being called
{
return string.Format("Object - {0}", x.ToString());
}
private string Test(Person x) //this is what you were hoping for
{
return string.Format("Person - {0}", x.ToString());
}
private string Test(Organization x)
{
return string.Format("Org - {0}", x.ToString());
}
一种解决方法是(不推荐):
public void Demo()
{
var myInstance = Activator.CreateInstance((new Person()).GetType());
Console.WriteLine(Test(myInstance));
}
private string Test(object x) //redirect the call to the right method
{
if (x is Person)
return Test(x as Person);
else
return Test(x as Organization);
}
private string Test(Person x) { return string.Format("Person - {0}", x.ToString()); } //this is what you were hoping for
private string Test(Organization x) { return string.Format("Org - {0}", x.ToString()); }
一个更好的解决方案是:
public interface ITestMethod { string Test();}
public class Person : ITestMethod
{
public Person() { }
public string Test() { return string.Format("Person - {0}", this.ToString()); }
}
public class Organization : ITestMethod
{
public Organization() { }
public string Test() { return string.Format("Org - {0}", this.ToString()); }
}
//...
public void Demo()
{
var myInstance = Activator.CreateInstance((new Person()).GetType()) as ITestMethod;
Console.WriteLine(myInstance.Test());
}
//...