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

2019-02-05 17:08发布

问题:

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:

You can use simplicity:

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