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

喜你入骨 提交于 2019-12-03 19:11:33

问题


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
}

回答1:


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)) {
  .......
}



回答2:


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
}



回答3:


Fast way might be:

if (_owner is null)
{

}



回答4:


You can use simplicity:

var s = data.servicePhoneNumber is null ? "" : data.servicePhoneNumber.Value;


来源:https://stackoverflow.com/questions/7029699/c-how-to-perform-a-null-check-on-a-dynamic-object

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