Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

What are the best practices for using Extension Methods in .Net?

I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a point).

So, what do you think are the best practices for employing Extension Methods?

Should development teams create a library of extension methods and deploy them across various projects?

Should there be a collection of common extension methods in the form of an open source project?

Update: have decided to create an organization wide extension methods library

question from:https://stackoverflow.com/questions/3147/what-are-the-best-practices-for-using-extension-methods-in-net

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

1 Reply

0 votes
by (71.8m points)

The upcoming release of the Framework Design Guidelines, 2nd Edition will have some guidance for implementing extension methods, but in general:

You should only define extension methods "where they make semantic sense" and are providing helper functionality relevant to every implementation.

You also should avoid extending System.Object as not all .NET languages will be able to call the extension method as an extension. (VB.NET for instance would need to call it as a regular static method on the static extension class.)

Don't define an extension method in the same namespace as the extended type unless you're extending an interface.

Don't define an extension method with the same signature as a "real" method since it will never be called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...