如何防止.NET基类使用? [英] How to prevent .NET base class usage?
问题描述
我正在一个项目中,我需要扩展WebClient
来实现自定义实现MyWebClient
.
I'm working on a project where I need to extend WebClient
for a custom implementation, MyWebClient
.
我还需要确保MyWebClient
是项目中任何开发人员都实现的唯一版本,并且没有人使用基WebClient
类.
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.
考虑到不是我可以访问的代码,是否可以防止使用WebClient
?
Is it possible to prevent the usage of WebClient
, considering it's not code that I have access to?
推荐答案
根据您需要的WebClient
功能,您可以考虑将MyWebClient
作为代理实现,该代理仅公开允许您使用的MyWebClient
方法. c0>成员.
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.
示例:
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.
}
之后,您将需要一个专用的ctor和一个工厂来正确实例化MyWebClient
.
After, you will need a dedicated ctor and a maybe a factory to instantiate MyWebClient
properly.
这不会阻止您的开发人员使用WebClient
,这太困难了(例如,请参阅@gdoron建议),但将有助于避免错误使用它.
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.
从您的最后一条评论中,我认为您只需要一个Factory即可为所有WebClient
实例设置用户代理.
From your last comment, I think that all you need is a Factory that will set the User Agent for all your WebClient
instances.
然后,根据您所在的组织,您需要就其使用情况进行深入的交流(也许还需要一个搜索工具来在项目中查找new WebClient()
).
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;
}
}
这篇关于如何防止.NET基类使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!