C# Type as object with indexer

xMi*_*hal 2 c# indexer

Consider a situation: I have a method which use DataRow:

public void MyMethod (DataRow input)
{
    DoSomething(input["Name1"]);
}
Run Code Online (Sandbox Code Playgroud)

But now I have some another input types with indexer which I want to pass to this method. St like:

public void MyMethod (AnyTypeWithIndexer input)
{
    DoSomething(input["Name1"]);
}
Run Code Online (Sandbox Code Playgroud)

But I haven't found anything like that. I tried IDictionary but it didn't work. Is there any super type st like "Indexable" or anything with which I can replace the "AnyTypeWithIndexer"?

Note: I still need this method to pass the DataRow and also my custom class (which I want to implement).

Can anybody help?

Thanks.

Hei*_*nzi 5

不,不幸的是,没有一个接口可以自动应用于“具有接受字符串参数并返回对象的索引器的所有类”

但是,您可以做的是创建一个自己实现此类接口的“代理类”:

public interface IStringToObjectIndexable
{
    object this[string index] { get; set; }
}

class DataRowWrapper : IStringToObjectIndexable
{
    private readonly DataRow row;

    public DataRowWrapper(DataRow row) => this.row = row;

    public object this[string index]
    {
        get => row[index];
        set => row[index] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

MyMethod 现在可以声明如下:

public void MyMethod(IStringToObjectIndexable input)
{
    DoSomething(input["Name1"]);
}

// Compatibility overload
public void MyMethod(DataRow input) => MyMethod(new DataRowWrapper(input));
Run Code Online (Sandbox Code Playgroud)