using System;
public abstract class BaseClass {
private string m_Name;
protected BaseClass(string name) {
m_Name = name;
}
public void Output()
{
Console.WriteLine("The class is: " + this.GetType());
Console.WriteLine("The name is: " + m_Name);
}
}
public class DerivedA : BaseClass {
public DerivedA(string name) : base(name) {}
}
public class DerivedB : BaseClass {
public DerivedB(string name) : base(name) {}
}
public static class MyStaticClass {
public static T Create<T>(string name)
where T : BaseClass
{
return (T)Activator.CreateInstance(typeof(T), new[] { name });
}
}
class Test {
static void Main() {
var a = MyStaticClass.Create<DerivedA>("derived a");
var b = MyStaticClass.Create<DerivedB>("derived b");
a.Output();
b.Output();
}
}
dXNpbmcgU3lzdGVtOwoKcHVibGljIGFic3RyYWN0IGNsYXNzIEJhc2VDbGFzcyB7CiAgICBwcml2YXRlIHN0cmluZyBtX05hbWU7CiAgICAKICAgIHByb3RlY3RlZCBCYXNlQ2xhc3Moc3RyaW5nIG5hbWUpIHsKICAgICAgICBtX05hbWUgPSBuYW1lOwogICAgfQogICAgCiAgICBwdWJsaWMgdm9pZCBPdXRwdXQoKQogICAgewogICAgICAgIENvbnNvbGUuV3JpdGVMaW5lKCJUaGUgY2xhc3MgaXM6ICIgKyB0aGlzLkdldFR5cGUoKSk7CiAgICAgICAgQ29uc29sZS5Xcml0ZUxpbmUoIlRoZSBuYW1lIGlzOiAiICsgbV9OYW1lKTsKICAgIH0KfQoKcHVibGljIGNsYXNzIERlcml2ZWRBIDogQmFzZUNsYXNzIHsKICAgIHB1YmxpYyBEZXJpdmVkQShzdHJpbmcgbmFtZSkgOiBiYXNlKG5hbWUpIHt9Cn0KCnB1YmxpYyBjbGFzcyBEZXJpdmVkQiA6IEJhc2VDbGFzcyB7CiAgICBwdWJsaWMgRGVyaXZlZEIoc3RyaW5nIG5hbWUpIDogYmFzZShuYW1lKSB7fQp9CgpwdWJsaWMgc3RhdGljIGNsYXNzIE15U3RhdGljQ2xhc3MgewogICAgcHVibGljIHN0YXRpYyBUIENyZWF0ZTxUPihzdHJpbmcgbmFtZS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