[英]Generic Methods, how to call a parent method without specifying a type
I have this parent class 我有这个家长班
public abstract class Parent
{
public string Id { get; set; }
public static T Find<T>(string id) where T : class, new()
{
/* logic here ..*/
}
}
and this child 还有这个孩子
public class Child : Parent
{
public string Name { get; set; }
}
Right now, the Find()
method can be called from child class like this Child.Find<Child>(myId);
现在,可以从子类中调用Find()
方法,例如Child.Find<Child>(myId);
What I need to change so it doesnt have to include class type like this Child.Find(myId);
我需要更改的内容,因此不必包括此类的类类型Child.Find(myId);
EDIT 编辑
I want to make this method as extension, and get it directly without defining the class into variable. 我想将此方法作为扩展,并直接获取而不将类定义为变量。 the generic class T
should be it's child type. 通用类T
应该是它的子类型。
Do you mean something like this: 您的意思是这样的吗:
public abstract class Parent
{
public string Id { get; set; }
public static Parent Find(string id)
{
/* logic here ..*/
}
}
This way you would have to cast the output to the correct type of derived class. 这样,您将不得不将输出强制转换为派生类的正确类型。 For example: 例如:
if(Parent.Find("123") is Child child)
{
child.Name = "TEST";
}
EDIT 编辑
Hide the inherited member and define a new one: 隐藏继承的成员并定义一个新成员:
public abstract class Parent
{
public string Id { get; set; }
public static Parent Find(string id)
{
/* logic here ..*/
}
}
public class Child : Parent
{
public string Name { get; set; }
public new static Child Find(string id)
{
/* logic here */
}
}
One option would be to add this method to your Child
class: 一种选择是将此方法添加到您的Child
类中:
public static Child Find(string id)
{
return Parent.Find<Child>(id);
}
I would do something like this: 我会做这样的事情:
public abstract class Parent<T> where T : class, new()
{
public T Find(string id)
{
return new T();
}
}
public class Child : Parent<Child>
{
public void Test()
{
var child = base.Find ("");
}
}
This would be the extension method approach: 这将是扩展方法:
public static class ExtensionMethods
{
public static T Find<T>(this T source, string id) where T : class, new()
{
return new T();
}
}
public class Child
{
public void FindChild()
{
this.Find("");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.