2017-07-06 98 views
0

我有这样的父类泛型方法,如何调用父类的方法不指定类型

public abstract class Parent 
{ 
    public string Id { get; set; } 

    public static T Find<T>(string id) where T : class, new() 
    { 
     /* logic here ..*/ 
    } 
} 

和这个孩子

public class Child : Parent 
{ 
    public string Name { get; set; } 
} 

眼下,Find()方法可以从子类被称为像这样Child.Find<Child>(myId);

我需要改变所以它不必包括像这样的类型Child.Find(myId);

编辑

我想使这个方法推广,并直接得到它没有确定类为可变。通用类T应该是它的子类。

+0

好了,你不能。您可以提供Find的非泛型重载,返回一个对象,但就是这样。 – Will

+0

你可以只调用查找() –

+0

我已经添加了扩展方法解决方案 –

回答

0

你的意思是这样的:

public abstract class Parent 
{ 
    public string Id { get; set; } 

    public static Parent Find(string id) 
    { 
     /* logic here ..*/ 
    } 
} 

这样,你就必须输出转换为正确的类型派生类的。例如:

if(Parent.Find("123") is Child child) 
{ 
    child.Name = "TEST"; 
} 

编辑

隐藏继承成员并定义一个新问题:

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 */ 
     } 
    } 
+0

我想使这个方法推广,并直接得到它没有确定类为可变。泛型类'T'应该是它的子类型。 – vantian

+0

或许从我的编辑解决方案?这可以让你为孩子定义一个全新的Find方法。扩展方法不能混合现有的方法 –

0

一种选择是,以这种方法添加到您的Child类:

public static Child Find(string id) 
{ 
    return Parent.Find<Child>(id); 
} 
0

我会做这样的事情:

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 (""); 
    } 
} 
0

这将是扩展方法的方法:

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(""); 
    } 
} 
相关问题