C#返回未知类型的子类(进一步:来自父类)
我有接口:C#返回未知类型的子类(进一步:来自父类),c#,types,return,parent,C#,Types,Return,Parent,我有接口: public interface Inx<T> { T Set(Data data); } 还有像这样的父类: public class Parent : Base, Inx<Parent> { ... } list.Add(new Parent().Set(data)); this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[]
public interface Inx<T>
{
T Set(Data data);
}
还有像这样的父类:
public class Parent : Base, Inx<Parent>
{
...
}
list.Add(new Parent().Set(data));
this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[] { data })
现在我必须这样做:
T t = new T();
t.Set(data);
list.Add(t);
而且它有点烦人,我不得不多次使用它
抱歉发垃圾邮件嗯,我可以用这样的东西:
public class Parent : Base, Inx<Parent>
{
...
}
list.Add(new Parent().Set(data));
this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[] { data })
所以,也许好的解决方法是从这个方法返回一个对象;\
好吧,带有泛型接口的泛型类似乎是巨大的内存浪费。。。因为这个类的函数是相同的,但返回类型是不同的。唯一的方法是将
Base
设置为泛型(Base
),并设置returnT
——然后设置Parent:Base
。问题是。。。Set
如何知道如何创建T
?您可以使用where T:new()
子句
这里一个有用的旁白是,您可以将接口实现移动到Base
:
公共类基:Inx其中T:new()
{
公共T集(数据){
T=新的T();
///
返回t;
}
}
公共类父级:基{}
这就是你想要的吗
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));
}
}
接口Inx{
T集(数据);
}
公共阶级基础
{
公共虚拟T集(数据)
{
T=默认值(T);
返回t;
}
}
公共类父级:基,Inx
{
公共父集合(数据)
{
返回base.Set(数据);
}
}
班级计划
{
静态void Main(字符串[]参数)
{
var data=新数据();
var list=新列表();
list.Add(newparent().Set(data));
//或
list.Add(newparent().Set(data));
}
}
编辑:最好将接口实现向上移动到基类,如Marc所说:
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));
}
}
接口Inx{
T集(数据);
}
公共类基:Inx
{
公共虚拟T集(数据)
{
T=默认值(T);
返回t;
}
}
公共类父级:基
{
}
班级计划
{
静态void Main(字符串[]参数)
{
var data=新数据();
var list=新列表();
list.Add(newparent().Set(data));
}
}
如果我使用泛型基类,我不能将父类强制转换为一种类型,
我不知道为什么我试着在那里使用泛型。。。我现在找到了解决办法:)
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));
// ...
}
接口Inx
{
对象集(数据);
}
阶级基础
{
对象集(数据)
{
// ...
返回(对象)这个;
}
}
父类:基,Inx
{
//我没有太多的write-here设置(我使用的是base-one)
}
类ManageParent,其中T:Inx,new()
{
// ...
list.Add((T)new T().Set(data));
// ...
}