gpt4 book ai didi

c# - 获取从抽象类继承并在属性中具有特定值的类的实例

转载 作者:行者123 更新时间:2023-11-30 14:22:20 27 4
gpt4 key购买 nike

我正在一家工厂工作,根据两个标准创建具体实例:

1)类必须继承自具体的抽象类

2) 类必须在覆盖的属性中有一个特定的值

我的代码是这样的:

public abstract class CommandBase
{
public abstract string Prefix { get; }
}

public class PaintCommand : CommandBase
{
public override string Prefix { get; } = "P";
}

public class WalkCommand : CommandBase
{
public override string Prefix { get; } = "W";
}

class Program
{
static void Main(string[] args)
{
var paintCommand = GetInstance("P");
var walkCommand = GetInstance("W");

Console.ReadKey();
}

static CommandBase GetInstance(string prefix)
{
try
{
var currentAssembly = Assembly.GetExecutingAssembly();
var concreteType = currentAssembly.GetTypes().Where(t => t.IsSubclassOf(typeof(CommandBase)) &&
!t.IsAbstract &&
t.GetProperty("Prefix").GetValue(t).ToString() == prefix).SingleOrDefault();

if (concreteType == null)
throw new InvalidCastException($"No concrete type found for command: {prefix}");

return (CommandBase)Activator.CreateInstance(concreteType);
}
catch (Exception ex)
{
return default(CommandBase);
}
}
}

我收到错误:

{System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

最佳答案

更简洁的方法是定义您自己的属性来存储前缀。

[AttributeUsage(AttributeTargets.Class)]
public class CommandAttribute : Attribute
{
public String Prefix { get; set; }

public CommandAttribute(string commandPrefix)
{
Prefix = commandPrefix;
}
}

然后像这样使用它们:

[CommandAttribute("P")]
public class PaintCommand : CommandBase
{}

[CommandAttribute("W")]
public class WalkCommand : CommandBase
{}

反射(reflection):

static CommandBase GetInstance(string prefix)
{
var currentAssembly = Assembly.GetExecutingAssembly();
var concreteType = currentAssembly.GetTypes().Where(commandClass => commandClass.IsDefined(typeof(CommandAttribute), false) && commandClass.GetCustomAttribute<CommandAttribute>().Prefix == prefix).FirstOrDefault();

if (concreteType == null)
throw new InvalidCastException($"No concrete type found for command: {prefix}");

return (CommandBase)Activator.CreateInstance(concreteType);
}

关于c# - 获取从抽象类继承并在属性中具有特定值的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com