c# - 关于索引器和/或泛型的问题

标签 c# generics indexer

如何知道一个对象是否实现了索引器?我需要共享 DataRow 和 IDataReader 的逻辑,但它们不共享任何接口(interface)。

我也尝试过使用泛型,但不知道应该对 where 子句施加什么限制。

public class Indexer {
    // myObject should be a DataRow or a IDataReader
    private object myObject;
    public object MyObject {
        get { return myObject; }
        set { myObject = value; }
    }
    // won't compile, myObject has no indexer
    public object this[int index] {
        get { return myObject[index]; }
        set { myObject[index] = value; }
    }
    public Indexer(object myObject) {
        this.myObject = myObject;
    }
}

public class Caller {
    void Call() {
        DataRow row = null;
        IDataReader reader = null;
        var ind1 = new Indexer(row);
        var ind2 = new Indexer(reader);
        var val1 = ind1[0];
        var val2 = ind1[0];
    }
}

最佳答案

您需要声明一个具有索引器属性的接口(interface),将该接口(interface)用作约束,并且类型参数类需要实现该接口(interface)以满足约束。

因为您无法控制要使用的类,所以这是行不通的。

另一种方法是让 Indexer 类将 get/set 操作作为单独的参数:

public class Indexer {

    private Func<int, object> getter;        
    private Action<int, object> setter;

    public object this[int index] 
    {
        get { return getter(index); }
        set { setter(index, value); }
    }

    public Indexer(Func<int, object> g, Action<int, object> s) 
    {
        getter = g;
        setter = s;
    }
}

public static class IndexerExtensions
{
    public static Indexer ToIndexer(this DataRow row)
    {
        return new Indexer(n => row[n], (n, v) => row[n] = v);
    }

    public static Indexer ToIndexer(this IDataReader row)
    {
        return new Indexer(n => row[n], (n, v) => row[n] = v);
    }
}

然后你可以这样做:

DataRow row = null;
IDataReader reader = null;
var ind1 = row.ToIndexer();
var ind2 = reader.ToIndexer();
var val1 = ind1[0];
var val2 = ind1[0];

关于c# - 关于索引器和/或泛型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687808/

相关文章:

c# - 避免在后台任务仍在运行时处理DbContext的更优雅的解决方案

c# - 是否可以将数据绑定(bind)到 Silverlight 中的方法?

java - 如何返回参数化返回类型的子类,其参数类型是返回类型参数类型的子类?

c - 带有 IAR 插件的 Eclipse 索引器

c++-cli - C++/CLI : Implementing IList and IList<T> (explicit implementation of a default indexer)

c# - 在 C# 中使用通配符获取动态生成文件的字符串?

c# - 通用类和 Type.GetType()

c# - 通用类型与扩展方法

c# - 索引器是否应该始终引用离散序列?

c# - 使用 Nodejs 解压缩使用 C# 代码片段压缩的字符串