Partial Class vs Extension Method

前端 未结 9 1688
無奈伤痛
無奈伤痛 2021-02-01 02:09

I dont have much experience of using these 2 ways to extend a class or create extension methods against a class. By looking others work, I have a question here.

I saw pe

9条回答
  •  醉酒成梦
    2021-02-01 02:13

    Partial works only if both files are in the same project, and you can access private and protected members of that class.

    Extension methods are just static methods, and can't access private members.

    So if you want to access private and protected members, only way you have is partial, if no, answer to the question, should the method you want to add be visible everywhere you want to use class? if yes, use partial, if no, it's some kind of extension, use extension methods.

    By the way, if the first class is not generated by some tool, you can write your function there except of using partial ;)

    hope this helps

提交回复
热议问题