2016-07-07 11 views
0

我在2个不同的文件中有2个类。调用基于ID的字典中​​存储的方法使用c#

  1. InvokeMethod:从Main()接收字节数组(换算成这里诠释actionID)和应该调用存储在基于所述actionID字典中的方法。这个类应该只有通用代码,以便它可以接受任何数量的方法和对象。

  2. ListOfMethods:添加接口实现中的所有方法,并返回带有键值对的字典。

  3. Main方法应该只有im.checkID(dataFromString("00 00 00 00")); 我已经做了字节数组转换字符串(即为什么我没有把它放在这里)。

InvokeMethod应该调用存储在词典基础上actionID方法。

的InvokeMethod

public class InvokeMethod 
{ 
    public void checkID(byte[] data) 
    { 
     int actionID = BitConverter.ToInt32(data, 0);      
     Console.WriteLine("action id {0}", actionID); 
     ListOfMethods GetMethods = new ListOfMethods(); 
     Dictionary<int, dynamic> methodList = GetMethods.ReturnMethods(actionID); 

     //here it should call the method from dictionary based on actionID. 

    } 
} 

ListOfMethods

public class ListOfMethods 
{ 
    Dictionary<int, dynamic> MethodDictionary = new Dictionary<int, dynamic>(); 
    Control ControlImplObj = new ControlImpl(); 
    Type ControlType = typeof(ControlImpl); 
    public Dictionary<int, dynamic> ReturnMethods(int actionID) 
    { 
     var methods = ControlImplObj.GetType().GetMethods(); 

     foreach (var item in methods.Select((value, index) => new { index, value })) 
     { 
      if (item.value.DeclaringType == typeof(ControlImpl)) 
      { 
       MethodDictionary.Add(item.index, item.value); 

      } 
     } 

     return MethodDictionary; 
    } 
} 

控制接口

interface Control 
{ 
    string SetTime();//0 
    string Nop();//1 
} 

控制接口实现

public class ControlImpl : Control 
{ 
    public string SetTime()      
    { 
     Console.WriteLine("inside SetTime "); 
     return null; 

    } 

    public string Nop()      
    { 
     Console.WriteLine("inside Nop "); 
     return null; 

    } 
} 

主要

static void Main(string[] args) 
    { 
     InvokeMethod im= new InvokeMethod(); 
     im.checkID(dataFromString("00 00 00 00")); 
     im.checkID(dataFromString("00 00 00 01")); 
     Console.ReadLine(); 
    } 
+0

随意发布尽可能多的新问题,但您可能希望在问题中包含所有必需的详细信息。将一个_open_问题作为一个论坛主题并不是通常的工作方式。 –

+0

@AdrianoRepetti我根据你以前的答案得到了解决方案。但你的答案似乎已被删除。该线程现在可以关闭。 –

回答

0

好像你认为存储方法作为dynamic将在能够使用常规,编译时语法来调用它们结束:x.Method(),但事实并非如此!

当你使用反射你正在获取元数据。它们不是的方法,而是可以用来调用它们的这些方法的元数据。

Type.GetMethods()为您提供了一个MethodInfo的数组,您可以调用如下方法:methodInfo.Invoke(instanceOfDeclaringType, new object[] { })其中给定数组中的每个索引都是方法的参数。如果方法为static,则可以调用null作为MethodInfo.Invoke的第一个参数。

相关问题