我有一个抽象的BaseClass,从中继承了多个派生类。 我想编写一个执行常见工作的泛型方法,这样我就不需要为每个派生类编写该方法。
当前代码 -
public abstract class BaseClass{}
public class Derived1 : BaseClass{
public Derived1 CommonWork(){
/* Common work */
return objDerived1;
}
}
public class Derived2 : BaseClass{
public Derived2 CommonWork(){
/* Common work */
return objDerived2;
}
}
我想要的方式 -
public T CommonWork where T : BaseClass
{
/* Common work */
return T;
}
现在我不知道如何以及在何处编写此方法。 Coudnt在其他地方找到它。 请建议。感谢
答案 0 :(得分:3)
你的意思是这样的:
public class CommonWork<T>
where T: BaseClass,
new T()// <- probably you'll need it to create instances of T
public T CommonWork(){
T result = new T();
...
return T;
}
}
...
Commonwork<Derived2> common = new Commonwork<Derived2>();
BaseClass result = common.CommonWork();
答案 1 :(得分:0)
您可以在BaseClass
中定义它,并在方法声明中包含泛型参数:
public T CommonWork<T>() where T : BaseClass {
T returnObj;
returnObj = default(T); // To initialize a new instance
returnObj = this as T; // To operate on the current object
/* Common work */
return returnObj;
}
答案 2 :(得分:0)
检查
class Program
{
static void Main(string[] args)
{
var derived1=new Derived1();
derived1.CommonWork();
var derived2 = new Derived2();
derived2.CommonWork();
Console.Read();
}
}
public abstract class BaseClass
{
public string ClassName;
public T CommonWork<T>(T obj)
{
var baseClass = obj as BaseClass;
Console.WriteLine( baseClass.ClassName);
return obj;
}
}
public class Derived1 : BaseClass
{
public Derived1 CommonWork()
{
this.ClassName = "Derived1";
return this.CommonWork(this);
}
}
public class Derived2 : BaseClass
{
public Derived2 CommonWork()
{
this.ClassName = "Derived2";
return this.CommonWork(this);
}
}
答案 3 :(得分:0)
这是在基类中完成常见工作的方式,但该方法返回派生类对象:
public abstract class BaseClass<T> where T: BaseClass<T>, new()
{
public int Value { get; private set; }
public T CommonWork()
{
var result = new T {Value = 1};
return result;
}
}
public class Derived1 : BaseClass<Derived1>
{
}
public class Derived2 : BaseClass<Derived2>
{
}
你这样称呼它:
Derived2 derived2 = new Derived2();
Derived2 anOtherderived2 = derived2.CommonWork();
int value = anOtherderived2.Value; // 2