如何扩展类而不是实例?
可能的重复:
你可以将扩展方法设为静态/共享吗?
扩展方法太棒了! 请原谅我的无知,但到目前为止,我只发现您可以扩展一个类以允许在其实例上使用方法,但不能扩展类本身。
这就是我正在尝试做的事情。
我有一个像这样的枚举:
enum ViewType
{
Front_View,
Back_View
}
并且我已经创建了一个扩展方法 ToDescription()
来显示视图类型的用户友好的文本表示,如下所示:
ViewType thisview = ViewType.Front_View;
string thisviewtext = thisview.ToDescription(); // translates to "Front View"
但在代码的后面,我想解析从该翻译回到类型,如果假设我可以扩展枚举类型本身,就像这个潜在的代码:
// !!!NOT REAL CODE YET!!!
// translate to value ViewType.FrontView
ViewType newview = ViewType.ParseFromDescription("Front View");
How do I Implement that ParseFromDescription(string)
扩展方法(如果可能)?
Possible Duplicate:
Can you make an Extension Method Static/Shared?
Extension methods are great!
Pardon my ignorance, but so far I've only found that you can extend a class to allow methods on its instances, but not the class itself.
Here's what I'm trying to do.
I have an enum like so:
enum ViewType
{
Front_View,
Back_View
}
And I already created an extension method ToDescription()
to display a user-friendly textual representation of the view type, like so:
ViewType thisview = ViewType.Front_View;
string thisviewtext = thisview.ToDescription(); // translates to "Front View"
But later in the code, I want to parse from that translation back to the type, like this potential code if assuming I can extend the enum type itself:
// !!!NOT REAL CODE YET!!!
// translate to value ViewType.FrontView
ViewType newview = ViewType.ParseFromDescription("Front View");
How do I implement that ParseFromDescription(string)
extension method (if possible)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能那样做。您可以定义一个包含该方法的静态帮助器类 ViewTypeTools。扩展方法基本上是相同的东西,但写起来更好一些。
You can't do that. You could define a static helper class ViewTypeTools containing the method. Extension methods are basically the same thing, but a bit nicer to write.
您不能使静态方法可调用,就像它包含在另一个静态类中一样。例如,您不能创建一个 String.IsNullOrBlank() 函数来检查传递的字符串除了是否为空或零长度之外是否仅包含空格。您必须有权访问 String 类代码并在其中添加方法。
为了获得您想要的结果,我将从字符串开始并实现一个扩展方法 ParseDescriptionToViewType() ,该方法将字符串作为其“this”参数并输出 ViewType。
You cannot make a static method callable as if it were contained in another static class. You cannot, for instance, create a String.IsNullOrBlank() function that checks the passed string for only whitespace in addition to being null or zero-length. You would have to have access to the String class code and add the method there.
To get the result you want, I would start with the string and implement an extension method ParseDescriptionToViewType() that will take the string as its "this" parameter and output the ViewType.
我没有测试但我认为会起作用的另一个选项(kludgy)
Another option (kludgy) that I didn't test but I think will work