我在2個不同的文件中有2個類。調用基於ID的字典中存儲的方法使用c#
類
InvokeMethod
:從Main()
接收字節數組(換算成這裏詮釋actionID
)和應該調用存儲在基於所述actionID
字典中的方法。這個類應該只有通用代碼,以便它可以接受任何數量的方法和對象。類
ListOfMethods
:添加接口實現中的所有方法,並返回帶有鍵值對的字典。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();
}
隨意發佈儘可能多的新問題,但您可能希望在問題中包含所有必需的詳細信息。將一個_open_問題作爲一個論壇主題並不是通常的工作方式。 –
@AdrianoRepetti我根據你以前的答案得到了解決方案。但你的答案似乎已被刪除。該線程現在可以關閉。 –