Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

c# - Partial Class vs Extension Method

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 people using a partial class to extend an entity class in a project. Meanwhile, in the same project, there is another folder containing a lot extension methods to the entity class.

Is it right to do so? I mean these 2 ways both work well. Could you give me some real idea of how to pick one or the other when I want extend a class?

question from:https://stackoverflow.com/questions/6017673/partial-class-vs-extension-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some of differences that will determine whether you want to use a Partial Class or an Extension Method are

Partial Class

  • Only works against classes in the same project/assembly
  • Target class has to be marked as partial
  • Has access to the Target class' fields and protected members
  • Target must be a class implementation

Extension Method

  • Can be applied against classes in other assembles
  • Must be static, has access to only the Target classes public members
  • Target of extension can be a concrete type, or an abstract type or interface

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...