【问题标题】:Dynamic object doesn't contain a definition for a property from a reference动态对象不包含来自引用的属性的定义
【发布时间】:2020-08-13 19:16:51
【问题描述】:

我得到的错误:

“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();
            }
        }
    }
}

【问题讨论】:

  • CallOfDuty类的定义在哪里?

标签: c# object dynamic


【解决方案1】:

它应该基本上按照你的方式工作。但是,如果不是这样,这里有一些替代方案。

您可以在c#中使用反射来获取动态对象的所有属性。

var nameOfProperty = "test";
var propertyInfo = game.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(game, null);

而且,如果你知道属性名,你可以简单地使用这种方式来获取值

string value = game["test"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 2015-11-27
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多