C#-在子类中指定超类的类型参数? [英] C# - Specifying type parameters of super-class in sub-classes?

查看:96
本文介绍了C#-在子类中指定超类的类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C#中执行以下操作.

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>
{
}

我该怎么办?

推荐答案

这很好:

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

public class Child : Parent<Child>
{
}

请注意这一点,因为c#不会强制执行真正的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.

这篇关于C#-在子类中指定超类的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆