Pass Generic键入继承树

时间:2017-01-05 03:06:37

标签: c# generics inheritance

我有以下课程:

abstract class Foo<T>
abstract class BaseClass : Foo<BaseClass>
class DerivedOne : BaseClass
class DerivedTwo : BaseClass

使用此结构,派生自BaseClass的所有类都继承自Foo<BaseClass>。我希望能够在每个派生类

中设置不同的T泛型类型

例如,在DerivedOne中,我希望课程为Foo<DerivedOne>,但在DerivedTwo中,我希望课程来自Foo<DerivedTwo>

有没有办法在继承树上传递泛型类型?

我尝试过这样的事情(这不起作用)。

abstract class Foo<T>
abstract class BaseClass<T> : Foo<T>
class DerivedOne : BaseClass<DerivedOne>
class DerivedTwo : BaseClass<DerivedTwo>

编辑:更改泛型类型以显示它们自己作为泛型类型传递

编辑#2:这是我正在使用的实际类的代码示例:

public abstract class DBObject<T> 
    where T : DBObject<T>, new()
{ 
    //the generic type is for this method, so I can create an object from a database query
    public static T Create(DataRow dataRow)
    {
        Type T = MethodBase.GetCurrentMethod().DeclaringType;
        T obj = new T();

        foreach (var field in obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            if (dataRow.Table.Columns.Contains(field.Name))
            {
                Object safeObj = Convert.ChangeType(dataRow[field.Name].ToString(), field.FieldType);
                field.SetValue(obj, safeObj);
            }

        }

        foreach (var field in obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            Console.WriteLine(field.Name + "=" + field.GetValue(obj));
            //propInfo.SetValue(obj, value, null);
        }
        return obj;            
    }
}

public abstract class Contact<T> : DBObject<T> 
    where T : Contact<T>
{ 
    //field and methods ommitted...
}

public class Person : Contact<Person>
{ 
    //fields and methods ommitted...
}

public class Company : Contact<Company>
{
    //fields and methods ommitted...
}

然后可以以这种方式使用这些类:

Person person = Person.Create(/* DataRow from a query result */);

1 个答案:

答案 0 :(得分:1)

如果您将new()约束添加到Contact<T>,我会编译您的代码:

public abstract class Contact<T> : DBObject<T> 
    where T : Contact<T>, new()
{ 
    //field and methods ommitted...
} 

这是必要的,因为DATEDIFF