簡體   English   中英

攔截動態調用以避免RuntimeBinderException

[英]Intercept a dynamic call to avoid RuntimeBinderException

當調用的方法或屬性不存在時,我想攔截對動態類型的調用以避免RuntimeBinderException。 例如:

class Foo {
    bool IsFool{ get; set; }
}
...
dynamic d = new Foo();
bool isFool = d.IsFoo; //works fine
bool isSpecial = d.IsSpecial; //RuntimeBinderException

我想做的就是在調用時創建不存在的屬性,或者只返回null。

編輯 :我想做的項目是一個配置文件閱讀器。 因此,我希望這避免嘗試嘗試捕獲或檢查配置文件的每個屬性是否存在。

除了在try .. catch塊中進行處理外,我看不到任何特殊方法

try 
{
  bool isSpecial = d.IsSpecial;
  return isSpecial;
}
catch(RuntimeBinderException)
{
  // do something else
  return false;
}

(OR)使用System.Reflection命名空間

        bool isSpecial = typeof(Foo)
                         .GetProperties()
                         .Select(p => p.Name == "IsSpecial").Count() > 0 
                         ? d.IsSpecial : false;

根據您的帖子編輯; 不知道這有多優雅,但是您可以在App.ConfigWeb.Config文件中定義一個AppSetting元素,例如

<configuration>
  <appSettings>
    <add key="IsFool" value="Foo"/>
    <add key="Display" value="Foo"/>
  </appSettings>
</configuration>

然后可以讀取該內容以驗證成員是否存在,然后進行相應的調用

        dynamic d = new Foo();

        bool isSpecial = System.Configuration.ConfigurationManager.AppSettings
                         .AllKeys.Contains("IsSpecial") 
                         ? d.IsSpecial : false;

通常,異常會花費大量時間嘗試檢查屬性是否存在:

public static bool HasProperty(this object obj, string propertyName)
{
    return obj.GetType().GetProperty(propertyName) != null;
}

在這里找到答案: https : //stackoverflow.com/a/1110504/818088
我必須擴展DynamicObject並覆蓋TryInvokeMember

最簡單的方法是將其轉換為JSON動態對象:

public static class JsonExtensions
{
    public static dynamic ToJson(this object input) => 
         System.Web.Helpers.Json.Decode(System.Web.Helpers.Json.Encode(input));

    static int Main(string[] args) {
         dynamic d = new Foo() { IsFool = true }.ToJson();
         Console.WriteLine(d.IsFool); //prints True
         Console.WriteLine(d.IsSpecial ?? "null"); //prints null
    }
}

class Foo
{
    public bool IsFool { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM