C#限制运行时中的泛型类型



我需要限制在RunTime中可以在构造函数中放入的内容。我有简单的课程:

class Human
{
public string Name { get; set; } = "John";
public int Age { get; set; } = 20;
public bool IsAlive { get; set; } = true; 
public override string ToString()
{
return $"Name: {Name}, Age: {Age}, Is alive: {IsAlive}";
}
}

class Animal
{
public string Type { get; set; } = "Bat";
public int Weight { get; set; } = 33;
public bool IsAlive { get; set; } = true;
public override string ToString()
{
return $"Type: {Type}, Weight: {Weight}, Is alive: {IsAlive}";
}
}

class Generics<T> where T : class, new()
{
public Generics()
{
T type = new T();
Console.WriteLine(type.GetType());
Console.WriteLine(type.ToString());
}
}

用户有没有办法在RunTime中说"T型只能是人类"或者"T型只能是动物。"。因此,如果用户(例如在switch中(说"类型T只能是人类",那么尝试创建构造函数(其中类型T是动物(将导致错误。

或者,如果用户说"T型只能是动物",那么试图创建构造函数(其中T型是人类(将导致错误。

另一个例子:用户说:"T型只能是动物":

然后执行:Generics<Human> human = new Generics<Human>();将导致错误。

当然,如果用户说"T型只能是人类",这将导致错误:

Generics<Animal> animal = new Generics<Animal>();

我不知道这是否可能,但如果你有解决方案,我会很高兴。非常感谢。

由于您希望在运行时限制泛型,那么我想您也希望该错误是

执行时在某处声明属性/字段,如下所示:

public Type TypeMustBe { get; set; }

在运行时,要说"T必须是Animal",您需要:

TypeMustBe = typeof(Animal);

同样,要说"T必须是Human",您需要:

TypeMustBe = typeof(Human);

在构造函数中,您可以执行以下操作:

if (typeof(T) != TypeMustBe) {
throw new Exception($"T must be {TypeMustBe}!");
}

但我认为这有点失去了泛型的意义。也许重新考虑一下你的设计?

您可以约束该方法,或者只检查给定T 的类型

public class Creator
{
public static T CreateHuman<T>()
where T : Human, new()
{
return new T();
}
public static T CreateAnimal<T>()
where T : Animal, new()
{
return new T();
}
public static T Create<T>()
where T : class, new()
{
switch (typeof(T))
{
case Type t when t == typeof(Human):
//throw new Exception("Type can be only Animal");
break;
case Type t when t == typeof(Animal):
//throw new Exception("Type can be only Human");
break;
}
return default(T);
}
}
}

最新更新