【问题标题】:.Net class helper method.Net 类辅助方法
【发布时间】:2009-07-20 19:54:55
【问题描述】:
有没有办法在类中添加方法,但仍允许它被基类继承?
我有以下
public class ListWithRandomize<T> : List<T> {
public void Randomize() { // Randomize function}
}
我将有一堆需要随机化的 List 对象。是否有可能有一个我可以“制作”到 ListWithRandomize 对象的 List 对象?我想我可以将 randomize 函数设为静态并将它作为参数 List,但我希望将它作为类的方法.. 如果可能的话。
谢谢。
【问题讨论】:
标签:
.net
oop
inheritance
extension-methods
【解决方案1】:
extension method 是您在无法访问源代码时向类添加方法的唯一方法。
请记住,扩展方法并不是一个类型的实际成员——它看起来就像在您的源代码中一样。它不能访问私有或内部变量——至少,不是没有反射,但你可能不想这样做。
我想我可以将 randomize 函数设为静态,并将 List 作为参数,但如果可能的话,我希望将它作为类的方法。
在这种情况下,扩展方法可能是您最好的选择。
【解决方案2】:
听起来你想要一个扩展方法,例如
public static void Randomize(this List<T> list)
{
// ...
}
这是一个静态方法,看起来像是List<T> 上的一个实例方法。
【解决方案3】:
我认为C# 3.0 Extension method 会做你想要在这里完成的事情。
public static class MyListExtension {
public static void Randomize(this List<T> list){...}
}
【解决方案4】:
extension 方法呢?
public static void Randomize<T>(This IList<T> list)
{
//randomize
}
【解决方案5】:
扩展方法。您可以将 Randomize 方法添加到 List。此代码是在此处编写的,因此可能无法编译。不过它应该给你一个开始。
public static class Extenstions
{
public static List<T> Randomize<T>(this List<T> list)
{
// randomize into new list here
}
}