首页 > 解决方案 > 动态对象不包含来自引用的属性定义

问题描述

我得到的错误:

“object”不包含“test”的定义

在此处输入图像描述

我也尝试过game.test(),但我不断收到此错误

该解决方案分为两个不同的项目:

目标是从“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#objectdynamic

解决方案


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

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

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

此外,如果您知道属性名称,您可以简单地使用这种方式获取值

string value = game["test"];

推荐阅读