使用多种语言的动态对象时,有一个构造允许您获取属性的值,如果该属性不存在,则返回默认值.
我想知道在.NET中使用dynamic时是否有类似的方法/语法.我知道您可以将ExpandoObject强制转换为Dictionary,但有时无法保证动态对象是Expando.
public class SomeClass { public string ValidProperty { get; set; } } dynamic t = new SomeClass() { ValidProperty = "someValue" }; Console.WriteLine(t.Get("ValidProperty","doesn't exist")); // Prints 'someValue' Console.WriteLine(t.Get("InvalidProperty","doesn't exist")); // Prints 'doesn't exist'
解决方法
I want to kNow if there is a similar method/Syntax when working with dynamic in .NET. I kNow that you can cast an ExpandoObject to a Dictionary,but sometimes there is no guarantee that a dynamic object is an Expando.
并且也不能保证它是编译时对象.
您可以使用try / catch,但这甚至没有说明该属性的存在.动态对象的一个例子:
public class MyDynamic: DynamicObject { static int Count = 0; public override bool TryGetMember(GetMemberBinder binder,out object result) { result = Count++; if (binder.Name == "Test") { return Count % 2 == 0; } return false; } }
并假设你使用它
dynamic d = new MyDynamic(); try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
对d.Test的一些调用将返回一个值,一些将抛出异常.所以我会说,没有安全的方法来测试它,并且没有任何默认值可能不存在的方法.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。