【问题标题】:Can't dynamically invoke a method in c#无法在c#中动态调用方法
【发布时间】:2020-01-09 22:07:34
【问题描述】:

我有一个类,我想动态调用它的方法。但我做不到。我错过了什么吗?

public class P_WATER
    {
        private int[] jDS = new int[20];
        private int n;

        public int[] JDS { get => jDS; set => jDS = value; }
        public int N { get => n; set => n = value; }

        public void P_WATER1()
        {
          //something...
        }
    }
public class Test
{

    P_WATER P_WATERState1 = new P_WATER();
    PLibStateList.Add(P_WATERState1);

    // Try to invoke methods from each objects.
    foreach (object item in StateUtility.PLibStateList)
    {
        Type objType= item.GetType();
        objType.InvokeMember(objType.Name + "1", BindingFlags.InvokeMethod, null, item, null);
    }
}

当尝试调用该方法时,出现以下异常:

无法加载文件或程序集“System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一。系统找不到指定的文件。

但是我的程序集很好地绑定到了项目。

【问题讨论】:

  • 发布的代码无法编译,否则代码可以工作。将此代码发布到新项目中并尝试在那里重现问题。

标签: c# c#-4.0 reflection


【解决方案1】:

我在 VS2019(控制台应用程序)中尝试了相同的代码(几乎没有修改)并且工作得很好......很奇怪......检查 using 语句是否有歧义(以防万一):

using System;
using System.Collections.Generic;
using System.Reflection;

我的完整代码:

using System;
using System.Collections.Generic;
using System.Reflection;

namespace cant_dynamically_invoke_a_method_in_c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Test.InvokeStuff();
        }
    }

    public class P_WATER
    {
        private int[] jDS = new int[20];
        private int n;

        public int[] JDS { get => jDS; set => jDS = value; }
        public int N { get => n; set => n = value; }

        public void P_WATER1()
        {
            //something...
            Console.WriteLine("Success!");
        }
    }

    public class Test
    {
        public static void InvokeStuff()
        {
            // Needed to mock this up
            List<P_WATER> PLibStateList = new List<P_WATER>();

            P_WATER P_WATERState1 = new P_WATER();
            PLibStateList.Add(P_WATERState1);

            // Try to invoke methods from each objects.
            foreach (object item in PLibStateList)
            {
                Type objType = item.GetType();
                objType.InvokeMember(objType.Name + "1", BindingFlags.InvokeMethod, null, item, null);
            }
        }
    }
}

输入方法成功:

问候!

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多