因此,我正在尝试的是创建一个方法,它选择实现泛型类的类型,其特定泛型值只有在运行时才知道。
我试过这样的方法
public bool HasCommand(ITerminal owner)
{
var genericType = typeof(Command<>).MakeGenericType(owner.GetType());
var command = typeof(HelloCommand);
return command.GetInterfaces().Any(x => x.GetGenericTypeDefinition() == genericType
&& x.IsGeneric);
}hello命令如下所示
public class HelloCommand : Command<HallTerminal>但它总是返回假的。任何关于改变/做什么的解决方案。
编辑:命令类如下所示
public class Command<T>发布于 2020-01-19 17:58:42
解决了这个问题,但始终出现错误的问题是,Command (在HelloCommand中实现)不是一个干扰,因此总是错误的。
要解决这个问题,你可以
command.BaseType.IsEquivalentTo(genericType)发布于 2020-01-18 17:32:00
可以使用is运算符检查类是否与给定类型兼容:
public bool HasCommand(Terminal owner)
{
var gType = typeof(Command<>).MakeGenericType(owner.GetType());
var bType = typeof(HelloCommand);
if (owner is Command<HallTerminal>)
{
}
}举个例子:
public class Person<T>
{
public int Id { get; set; }
}
public class Student : Person<Greeting>
{ }
public class StudentWarmGreeting : Person<WarmGreeting>
{ }
public class Greeting
{
public void SayHello()
{
Console.WriteLine("Hello, it is Greeting!:)");
}
}
public class WarmGreeting
{
public void SayHello()
{
Console.WriteLine("Hello, it is WarmGreeting!:)");
}
}您可以使用is操作符进行检查:
static void Main(string[] args)
{
if (studentGreeting is Person<Greeting>)
Console.WriteLine("person is Greeting");
if (studentWarmGreeting is Person<WarmGreeting>)
Console.WriteLine("person is WarmGreeting");
// Visual Studio is clever and it will say:
// "The given expression is never of the provided ('Program.Person') type"
if (studentWarmGreeting is Person<Greeting>)
Console.WriteLine("person is Greeting");
}但是,Visual很聪明,它将给我们一个警告:
给定表达式从来不是提供的('Program.Person')类型的
https://stackoverflow.com/questions/59803043
复制相似问题