简体   繁体   中英

Intercept a dynamic call to avoid RuntimeBinderException

I want to intercept calls to a dynamic type to avoid a RuntimeBinderException when the method or property called does not exist. For example:

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

What I want to do is to either create the nonexistent property when called or to just return null.

EDIT : The project I'm trying to do is a configuration file reader. So I want this to avoid doing a try catch or check if exists to every property of the cofiguration file.

I don't see any special way than handling in try .. catch block like

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

(OR) Using System.Reflection namespace

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

Per your edit in post; not sure how elegant this would be but you can define a AppSetting element in App.Config or Web.Config file like

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

Then can read that to verify whether the member exists or not and then call accordingly

        dynamic d = new Foo();

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

Exception usualy take much time try to check if property exist:

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

Found the answer here: https://stackoverflow.com/a/1110504/818088
I have to extend the DynamicObject and override TryInvokeMember

Easiest way is to convert it into a JSON dynamic object:

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM