C#:如何对动态对象执行空检查
如何对动态对象执行空检查?
伪代码:
public void Main() {
dynamic dynamicObject = 33;
if(true) { // Arbitrary logic
dynamicObject = null;
}
Method(dynamicObject);
}
public void Method(dynamic param) {
// TODO: check if the content of 'param' is equal to null
}
How do I perform a null-check on a dynamic object?
Pseudo code:
public void Main() {
dynamic dynamicObject = 33;
if(true) { // Arbitrary logic
dynamicObject = null;
}
Method(dynamicObject);
}
public void Method(dynamic param) {
// TODO: check if the content of 'param' is equal to null
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否担心动态对象可能具有自定义相等运算符,该运算符会改变
null
的解释方式?如果是这样,只需使用Object.ReferenceEquals
Are you worried about the possibility the dynamic object will have a custom equality operator that will change the way the
null
is interpreted? If so just useObject.ReferenceEquals
您始终可以将参数设置为对象类型,这就是编译器正在做的事情。当您键入动态参数时,它仅意味着在该方法内仅对参数的所有使用使用动态调用,但在外部它只是类型对象的签名。 DynamicObject 的更强大用法是重载您正在调用的方法,因此,如果您保持示例相同并且只有两个重载,它将根据运行时类型调用这两个方法之一,并且您始终可以添加更多以获取更多类型。
You can always just make the param of type object, that's what the compiler is doing. When you type a parameter dynamic it just means within that method only it is using dynamic invoke for all uses of param, but outside it's just a signature of type object. A more powerful usage of your dynamicObject would be to have overloads of the method you are calling, so if you keep your example the same and just have two overloads it would call one of the two methods based on the runtime type, and you can always add more for more types.
您可以使用简单性:
You can use simplicity:
快速的方法可能是:
Fast way might be: