简体   繁体   中英

C# - Specifying type parameters of super-class in sub-classes?

I am trying to do the following in C#.

public class Parent<T> where T : Parent<???>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

How can I do it?

This works fine:

public class Parent<T> where T : Parent<T>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

Do be careful with this as c# does not enforce a true Parent / Child relationship. For example, given the above code, it is also legal for me to then do this:

public class Stranger : Parent<Child>
{
}

If you write unit tests then it's worth writing a type checker that looks for this mispattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM