C#: How to perform a null-check on a dynamic object

别说谁变了你拦得住时间么 提交于 2019-11-30 05:58:31
JaredPar

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 use Object.ReferenceEquals

if (Object.ReferenceEquals(null, param)) {
  .......
}

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.

public void Main() {
    dynamic dynamicObject = 33;
    if(true) { // Arbitrary logic
        dynamicObject = null;
    }
    Method(dynamicObject);
}
public void Method(int param) {
  //don't have to check check null
  //only called if dynamicObject is an int
}
public void Method(object param) {
// will be called if dynamicObject is not an int or null
}

Fast way might be:

if (_owner is null)
{

}
Ngô Thanh Tùng

You can use simplicity:

var s = data.servicePhoneNumber is null ? "" : data.servicePhoneNumber.Value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!