【发布时间】:2018-08-24 21:11:58
【问题描述】:
这是一个使用命令属性运行的命令系统。下面列出了其工作原理的示例。
如果您要在聊天中键入 /message,这将运行条目程序集中的方法,该方法包含文本值为“消息”的 CommandAttribute。所有使用 CommandAttribute 的类都继承自 CommandContext 类。使用反射,我试图设置 CommandContext 属性的值,以便它们可以在包含被调用的命令方法的派生类中使用。
在设置位于 CommandContext 类中的属性值时(在这种情况下为消息),我收到以下错误。
对象与目标类型不匹配
我已尝试其他问题的解决方案,但仍然收到错误消息。 我在下面发布了派生类、基类和方法。请让我知道是否需要任何其他信息来帮助我。谢谢大家的帮助。
此处发生错误:
messageProp.SetValue(baseType, Convert.ChangeType(rawMessage, messageProp.PropertyType), null);
命令属性
namespace RocketNET.Attributes
{
public class CommandAttribute : Attribute
{
public string Text { get; private set; }
public CommandAttribute(string text)
{
Text = text;
}
}
}
基类
namespace RocketNET
{
public class CommandContext
{
public string Message { get; internal set; }
public CommandContext() { }
}
}
派生类
namespace ACGRocketBot.Commands
{
public class Maintenance : CommandContext
{
[Command("message")]
public void SendMessage()
{
Console.WriteLine(Message);
}
}
}
方法
namespace RocketNET
{
public class RocketClient
{
private void MessageReceived(object sender, MessageEventArgs e)
{
string rawMessage = "/message";
if (rawMessage[0] == _commandPrefix)
{
var method = Assembly.GetEntryAssembly()
.GetTypes()
.SelectMany(t => t.GetMethods())
.FirstOrDefault(m =>
m.GetCustomAttribute<CommandAttribute>()?.Text == rawMessage.Substring(1).ToLower());
if (method != null)
{
method.Invoke(Activator.CreateInstance(method.DeclaringType), null);
var baseType = method.DeclaringType.BaseType;
var messageProp = baseType.GetProperty("Message");
messageProp.SetValue(baseType, Convert.ChangeType(rawMessage, messageProp.PropertyType), null);
}
}
}
}
}
【问题讨论】:
标签: c# .net reflection