考虑:
class BasicType
{
public BasicType() { }
public T Save<T>() where T : BasicType
{
BasicType b = DataContext.Save(this); //Returns a BasicType
return (T)Activator.CreateInstance(typeof(T), b);
}
}
class DerivedType : BasicType
{
public DerivedType(BasicType b) { }
}
public static void Main()
{
DerivedType d = new DerivedType();
d = d.Save<DerivedType>();
}
这样可行,但每次调用Save时被强制指定类型都是拖拽。 是否有某种方法可以更改BasicType.Save方法,以便它始终返回正在调用Save的实例的实际类型(派生或基础)的实例?
答案 0 :(得分:3)
在这种情况下不需要泛型。
我认为这应该足够了:
public BasicType Save()
{
BasicType b = DataContext.Save(this); //Returns a BasicType
return (BasicType)Activator.CreateInstance(this.GetType(), b);
}
无论如何你应该小心这个,因为继承的类可能没有预期的构造函数。
最好覆盖保存方法,或者至少是特定部分。
答案 1 :(得分:1)
您可以更改BasicType
的定义,以便在继承时强制提供T
的类型。
这样的事情:
class BasicType<T> where T : BasicType<T>, new()
{
public BasicType() { }
public T Save()
{
T b = new T();
return (T)Activator.CreateInstance(typeof(T), b);
}
}
class DerivedType : BasicType<DerivedType>
{
public DerivedType() { }
}
class Program
{
static void Main(string[] args)
{
DerivedType d = new DerivedType();
d = d.Save();
}
}
答案 2 :(得分:0)
像这样的东西。
class BasicType
{
public BasicType()
{
}
protected virtual T Save<T>()
{
BasicType b = DataContext.Save(this); //Returns a BasicType
return (T)Activator.CreateInstance(typeof(T), b);
}
}
class DerivedType : BasicType
{
public DerivedType(BasicType b)
{
}
public DerivedType Save()
{
return base.Save<DerivedType>();
}
}
public static void Main()
{
DerivedType d = new DerivedType(new BasicType());
d = d.Save();
}