![](/img/trans.png)
[英]call c# class method by reflection with constructor using dependency injection
[英]How to call a function in a singleton class, using reflection in c#
我嘗試通過反射在單例類中調用函數。 我得到以下異常:
System.Reflection.TargetInvocationException:調用的目標引發了異常。 ---> System.ArgumentException:具有相同鍵的條目已存在。
類和調用方法位於下面。 有人知道我在做什么錯嗎?
public class SetStatus{
private static readonly SetStatus instance = new SetStatus();
protected SortedDictionary<int, string> resources = new SortedDictionary<int, string>();
public static SetStatus Instance
{
get
{
return instance;
}
}
protected override void LoadResources()
{
resources.Add(0, MyApp.Resources.Localization.Approved);
resources.Add(1, MyApp.Resources.Localization.Rejected);
resources.Add(2, MyApp.Resources.Localization.Revoked);
}
public SetStatus()
{
LoadResources();
}
public SortedDictionary<int, string> Resources
{
get
{
return resources;
}
}
}
void ResetStaticEnums()
{
string methodName = "LoadResources";
MethodInfo method = typeof(SetStatus).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
method.Invoke(SetStatus.Instance, Type.EmptyTypes);
}
您不能多次向字典添加相同的鍵
protected override void LoadResources()
{
resources.Add(Convert.ToInt32(WeekStatus.AdministrationApproved), MyApp.Resources.Localization.Approved);
resources.Add(Convert.ToInt32(WeekStatus.AdministrationApproved), MyApp.Resources.Localization.Rejected);
resources.Add(Convert.ToInt32(WeekStatus.AdministrationApproved), MyApp.Resources.Localization.Revoked);
}
您正在添加AdministrationApproved 3次。
您兩次調用LoadResources
。
public SetStatus()
與private static readonly SetStatus instance = new SetStatus();
method.Invoke(SetStatus.Instance, Type.EmptyTypes);
這導致了異常:
具有相同鍵的條目已存在
刪除LoadResources();
在您的構造函數中,它將起作用(一次)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.