[英]How to force a type to be a subclass of another type in C#
有谁知道如何确保 Type 的值继承自超类的 Type?
public class MyClass {
private Type myType; // where the type is a subclass MySuperClass type
}
我知道如何在 Java 中使用:
private Class<? extends MySuperClass> clazz;
但我想知道如何在 C# 中做到这一点
您应该在以下位置使用:
class Myclass<Type> where Type: Superclass
文档: https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
回复 Skaparate,这不是我想要的。 我不想在我想使用类型作为属性的任何时候被迫创建一个新类(类型列表的示例)
所以我创建了一个类似于 java.lang.Class 的类,我会随时添加方法:
public class Class<T> where T : class {
public T newInstance()
{
return (T) Activator.CreateInstance(typeof(T));
}
public T newInstance(params object[] parameters)
{
return (T) Activator.CreateInstance(typeof(T), parameters);
}
public new Type GetType()
{
return typeof(T);
}
}
public abstract class Spell {
// as a battle animation's attributes changes during the animation I want to recreate a new one anytime this spell is used
private Class<BattleAnimation> animation;
public BattleAnimation GetAnimation() {
return this.animation.newInstance();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.