[英]Moving dynamic method call to class library causes a RuntimeBinderException in C#
[英]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.Config
或Web.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.