2009-06-20 68 views
2

我有接口:C#子类返回一个未知类型(futher:来自亲本)

public interface Inx<T> 
{ 
    T Set(Data data); 
} 

简单的类与此梅托德

public class Base 
{ 
    ??? Set(Data data) { ... } 
} 

和父类这样的:

public class Parent : Base, Inx<Parent> 
{ 
    ... 
} 

我想返回子类中的设置metod的父类型 这是可能的吗? 我需要做这样的事情:

list.Add(new Parent().Set(data)); 

现在我要做的是:

T t = new T(); 
t.Set(data); 
list.Add(t); 

而且它有点讨厌,我不得不使用它很多时候


对不起,我好可以使用类似的东西:

this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[] { data }) 

所以也许很好的解决方案是从这个方法返回一个对象; \?

与通用接口以及通用类看起来的要大浪费内存... beacose这个类的功能是相同的只有返回类型不同势

回答

0

这是你想要的吗?

interface Inx<T> { 
    T Set(Data data); 
} 
public class Base 
{ 
    public virtual T Set<T>(Data data) 
    { 
     T t = default(T); 
     return t; 
    } 
} 
public class Parent : Base, Inx<Parent> 
{ 
    public Parent Set(Data data) 
    { 
     return base.Set<Parent>(data); 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var data = new Data(); 
     var list = new List<Parent>(); 
     list.Add(new Parent().Set<Parent>(data)); 
     // or 
     list.Add(new Parent().Set(data)); 
    } 
} 

编辑:这是更好地移动接口实现了基类的马克说:

interface Inx<T> { 
    T Set(Data data); 
} 
public class Base<T> : Inx<T> 
{ 
    public virtual T Set(Data data) 
    { 
     T t = default(T); 
     return t; 
    } 
} 
public class Parent : Base<Parent> 
{   
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var data = new Data(); 
     var list = new List<Parent>(); 
     list.Add(new Parent().Set(data));    
    } 
} 
5

你能做到这将是使的唯一方法Base通用(Base<T> )并且有Set返回T - 然后有Parent : Base<Parent>。问题是... Set如何知道如何创建T?你可以有where T : new()条款等

有用抛开这里要说的是,你可以移动接口实现为Base<T>

public class Base<T> : Inx<T> where T : new() 
{ 
    public T Set(Data data) { 
     T t = new T(); 
     /// 
     return t; 
    } 
} 
public class Parent : Base<Parent> { } 
0

好,如果我使用了通用基础类,我不能投父类的一种类型, 我不知道为什么我试图使用通用的有...我发现解决方案现在:)

THX的帮助

interface Inx 
{ 
    object Set(Data data); 
} 
class Base 
{ 
    object Set(Data data) 
    { 
     // ... 
     return (object) this; 
    } 
} 
class Parent: Base, Inx 
{ 
    // i don't have too write here Set (im using from base one) 
} 
class ManageParent<T> where T: Inx, new() 
{ 
    // ... 
     list.Add((T) new T().Set(data)); 
    // ... 
}