c# - 动态对象不包含来自引用的属性定义
问题描述
我得到的错误:
“object”不包含“test”的定义
我也尝试过game.test()
,但我不断收到此错误
该解决方案分为两个不同的项目:
- 第一个是.dll
- 第二个是控制台
目标是从“iw4mp”类动态调用get方法。所以我可以在加载类时调用任何类。COD 类应该看起来没用,但将来它会查看进程是否在计算机上运行,但对于我的测试,我使用了一个字符串(但它实际上的工作方式与它正在寻找一个进程相同)。
DLL 中的代码
鳕鱼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
using CODOffsets.Offsets;
namespace CODOffsets
{
public class COD
{
static string[] games = { "iw4mp", "iw5mp", "bo1" };
static Type CallofDuty;
public static bool checkGame()
{
foreach (string game in games)
{
if (ProcessHandle(game))
{
CallofDuty = Type.GetType("CODOffsets.Offsets" + "." + game);
return true;
}
}
return false;
}
public static object Game()
{
return Activator.CreateInstance(CallofDuty) as ICODClass;
}
public static bool ProcessHandle(string game)
{
if (game == "iw4mp")
return true;
else
return false;
}
}
}
界面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CODOffsets.Interface
{
interface ICODClass
{
string test { get; }
}
}
抵消
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
namespace CODOffsets.Offsets
{
class iw4mp : ICODClass
{
public string test { get { return "this is mw2"; } }
}
}
来自控制台项目的代码
主要的
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets;
namespace TestGenericClass
{
class Program
{
static void Main(string[] args)
{
if (COD.checkGame())
{
dynamic game = COD.Game();
Console.WriteLine(game.test);
Console.ReadKey();
}
}
}
}
解决方案
它基本上应该像你一样工作。但是,如果不是这样,这里有一些替代方案。
您可以在 c# 中使用反射来获取动态对象的所有属性。
var nameOfProperty = "test";
var propertyInfo = game.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(game, null);
此外,如果您知道属性名称,您可以简单地使用这种方式获取值
string value = game["test"];
推荐阅读
- ios - ios 图表 - 在轴内部显示标签
- android - 我们可以在不给用户任何奖励的情况下使用 Admob 奖励广告吗?
- python - python HTTPServer return multipart/form-data(返回多个二进制文件)
- c++ - CppAD 中的固定大小特征矩阵
- ruby - 如何使用 RSpec 测试方法是否捕获符号?
- javascript - 在导航中计算过滤的行数
- java - 将 JFoenix JFXDialogLayout 警报通知代码重构为更简单的形式,以便可以将其重用于其他类
- javascript - 哪个会更快?
- reactjs - 使用 Typescript 和 Union 接口从 React 组件中解构 Props
- r - 如何在 dbplyr 中使用自定义 SQL 函数?