问题
I'm working on a project where I need to extend WebClient for a custom implementation, MyWebClient.
I also need to make sure that MyWebClient is the only version that's implemented by any developer on the project and no one uses the base WebClient class.
Is it possible to prevent the usage of WebClient, considering it's not code that I have access to?
回答1:
Depending on the features of WebClient you need, you could consider implementing MyWebClient as proxy that exposes only the methods you allow to be used from a WebClient member.
Example:
public class MyWebClient
{
private WebClient HiddenWebClient {get; set;}
// proxy sample
public void DownloadFile(string address, string fileName)
{
HiddenWebClient.DownloadFile(address, fileName);
}
// other proxy methods & your specific implementation come here.
}
After, you will need a dedicated ctor and a maybe a factory to instantiate MyWebClient properly.
This won't prevent your developers from using WebClient which would be far too difficult (see @gdoron suggestion, for instance), but will help avoiding its usage by mistake.
Edit:
From your last comment, I think that all you need is a Factory that will set the User Agent for all your WebClient instances.
Then, depending on your organization, you will need a strong communication about its usage (and maybe a search tool to look for new WebClient() in your projects).
public static class WebClientFactory
{
public static WebClient Create()
{
WebClient result = new WebClient();
result.Headers.Add("My Fancy User Agent");
return result;
}
}
回答2:
The best way to do this is to code review all the code and make sure that WebClient isn't being used. Another option is to schedule a nightly task and pull from the source control and search through each file in the project to see if they use WebClient instead of MyWebClient (might be easier to do using Roslyn). Bottom line is that this isn't a code issue (or shouldn't be) it should be a training issue.
回答3:
If you really need it, (which I seriously doubt it)The only way you can do it is with reflection.
When the application starts scan for the code of all the methods and classes in the Assembly, and check that they don't use the forbidden WebClient class.
I guess you won't do it...
回答4:
If you are using ReSharper, you could use the "Search with pattern" feature, and set it up to offer to automatically convert the WebClient code to your MyWebClient just by pressing the magical ALT+Enter shortcut!
See: http://www.jetbrains.com/resharper/webhelp/Reference__Search_with_Pattern.html
来源:https://stackoverflow.com/questions/9777766/how-to-prevent-net-base-class-usage