c# - 在 C# 中返回 'this' 的数组

标签 c# generics

我有一个包含类的库。此类旨在扩展。它将连接到数据库并生成扩展它的类的条目。现在我想返回一个扩展类类型的数组。我怎样才能做到这一点 ?例如:

public this[] search(string search) {
}

我该如何执行此操作?

编辑: 我正在使用泛型,它是一个泛型类。这意味着我不知道将扩展我的类(class)是什么。所以不,我不能只在 [] 之前添加类名...

编辑 2: 正如已经指出的那样,返回一个这样的数组没有任何意义(那是我的错误)。所以我想做的是返回一个扩展类类型的数组。 例如:

public abstract class MappingObject {
    public ExtendedClassType[] search (string search) {
    }
}

找到解决方案._。很抱歉,这很简单......

public abstract class MappingObject<T> where T : new() {
    public static List<T> search(string search) {
    }
}

最佳答案

我不完全确定您在寻找什么,但根据您问题中的一些线索,您可能想要查看类似以下内容(称为 Curiously Recurring Template Pattern ):

public abstract class MyBaseClass<T> : where T : MyBaseClass<T>
{
    public abstract T[] Search(string search);
}

public class DerivedClass : MyBaseClass<DerivedClass>
{
    public override DerivedClass[] Search(string search)
    {
        return new DerivedClass[0];
    }
}

这是可能的,但我不确定这是否是您正在寻找的东西,我会查看这是否是一个好的设计选择,感觉有点漏。

这种特殊的想法用于 CSLA.NET 等框架中,以便在从某些基类继承时向派生类公开对自身的强引用。这通常是一个“语法糖”的东西,并且避免了在从基类中检索它们时为了在您自己的类型上使用东西而不得不进行大量的转换。基类本身仍然不应该理解从它派生的类型。


Eric Lippert talks about this pattern on his old MS blog .它有它的陷阱,他揭露了它可以被滥用的方式。我个人支持这样一种方法,即意识到这些陷阱和滥用的可能性就足够了,只要经过测试,我很乐意使用可能违反指导方针或原则的东西,如果情况很清楚的话(没有足够的附加信息以了解在这种特殊情况下是否清楚)。 Eric 的帖子结束:

All that said, in practice there are times when using this pattern really does pragmatically solve problems in ways that are hard to model otherwise in C#; it allows you to do a bit of an end-run around the fact that we don't have covariant return types on virtual methods, and other shortcomings of the type system. That it does so in a manner that does not, strictly speaking, enforce every constraint you might like is unfortunate, but in realistic code, usually not a problem that prevents shipping the product.

My advice is to think very hard before you implement this sort of curious pattern in C#; do the benefits to the customer really outweigh the costs associated with the mental burden you're placing on the code maintainers?

我所见过的这种模式的最佳用法是将所有重复出现的部分留在内部或 protected ,而公共(public) API 则保持独立。

关于c# - 在 C# 中返回 'this' 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21378040/

相关文章:

java - 没有明确声明泛型类型的赋值如何被滥用?

java - Junit 测试用例 AssertionError 预期为 json 字符串

c# - [Computed] 和 [Write(false)] 属性之间有什么区别?

c# - 使用 LINQ 转换为 Int

c# - AutoMapper 扁平化扩展方法

ios - 无法推断通用参数 'T' Xcode 11 iOS 13

c# - 如何将谓词传递给 C# 中的函数?

c# - Nhibernate session.BeginTransaction() 与 transaction.Begin()

c# - 具有通用类型的 StructureMap OnCreation

java - 使用接受任何类作为参数的方法创建 Java 接口(interface)