Possible pitfalls of using this (extension method based) shorthand

后端 未结 11 1439
孤独总比滥情好
孤独总比滥情好 2020-11-27 20:00

C#6 Update

In C#6 ?. is now a language feature:

// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null; 

// C#         


        
11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 20:30

    it does make the code a little easier to read, but at the cost of extending object. This would appear on everything,

    Note that you are not actually extending anything (except theoretically).

    propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
    

    will generate IL code exactly as if it were written:

    ExtentionClass::IfNotNull(myObject2,  x => x.IntProperty, 0);
    

    There is no "overhead" added to the objects to support this.

提交回复
热议问题