これはあなたが抱えている問題ですか?
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());
}
1つの修正はこれです(推奨されません):
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());
}
//...