[英]If statement in Unity C# false, but true in Watch
我目前正在為 Unity3D 開發一個用戶界面編輯器。 在這一點上,我有一個字典,其中的鍵和值都代表一種類型。 基於鍵類型,我想將值類型的組件添加到游戲對象並返回它:
protected Dictionary<string, string> eventHandlers = new Dictionary<string, string>();
public virtual EventHandler GetHandler(System.Type type)
{
string name = type.Name;
if(eventHandlers.ContainsKey(name))
{
System.Type eventHandlerType = TypeUtility.GetType(eventHandlers[name], null);
return this.gameObject.AddComponent(eventHandlerType) as EventHandler;
}
return null;
}
問題在於我的 if 語句。 顯然, eventHandlers.ContainsKey(name) 返回 false,因為調用了 return null 語句。 但是,字典確實包含密鑰。 更奇怪的是:如果我在 Visual Studio 中將這個語句輸入到我的手表中,它是真的。
有人知道為什么我的 if 語句是假的,而在手表中是真的嗎? 有人能指出我正確的方向嗎?
[編輯] 值是:
name "IOnClick" System.String
eventHandlers
Count=1
System.Collections.Generic.Dictionary`2
[
[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],
[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
]
["IOnClick"] "OnClickHandler" System.Collections.DictionaryEntry
type "InterfaceEditor.EventSlots.IOnClick" System.Type
DeclaringMethod System.InvalidOperationException: DeclaringMethod can only be used on generic arguments System.Reflection.MethodBase
Name "IOnClick" System.String
[edit2] 所以,我找到了我的問題所在。
上面的代碼駐留在我的類 InterfaceElement 中:
public abstract class InterfaceElement : MonoBehaviour, ISerializationCallbackReceiver
{
protected Dictionary<string, string> eventHandlers = new Dictionary<string, string>();
}
對於我不同的 InterfaceElements,比如我的按鈕,我想我可以像這樣覆蓋字典:
public class Button : InterfaceElement, IOnClick
{
protected new Dictionary<string, string> eventHandlers = new Dictionary<string, string>()
{
{ typeof(IOnClick).Name, typeof(OnClickHandler).Name }
};
}
顯然,C# 或 Unity 不喜歡這樣。 做一些類似的事情的正確方法是什么? 我不能使用構造函數,因為我的 InterfaceElement 是 MonoBehaviour,對嗎?
所以。 事實證明, new 並沒有像我想象的那樣做。 New 不會覆蓋字段,而是隱藏基本字段。 這意味着基類仍然會看到基字段。 我的解決方案是不使用字段,而是使用返回字典的方法,如下所示:
public abstract class InterfaceElement : MonoBehaviour
{
protected virtual Dictionary<System.Type, System.Type> GetEventHandlers()
{
return null;
}
public virtual EventHandler GetHandler(System.Type type)
{
Dictionary<System.Type, System.Type> eventHandlers = GetEventHandlers();
if(eventHandlers != null && eventHandlers.ContainsKey(type))
return this.gameObject.AddComponent(eventHandlers[type]) as EventHandler;
return null;
}
}
public class Button : InterfaceElement, IOnClick
{
protected override Dictionary<System.Type, System.Type> GetEventHandlers()
{
return new Dictionary<System.Type, System.Type>()
{
{typeof(IOnClick), typeof(OnClickHandler)}
};
}
}
感謝您發表評論並幫助找到答案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.