C #: require indexer from method parameter

I am writing a function that is a converter from one type of object to another. An object that is passed as a parameter of the Map method must have a line pointer to find the corresponding value in the object (or not). I don't care if the cartographer gets a dictionary, DataRow, DataReader, etc.

Is there a way to indicate that the parameter passed to the method should implement a string index? I can not find anything like it.

I use reflection to give type to something useful, if that is not possible, but I was wondering if he has the right way to handle it.

+3
source share
4 answers

, . , , Andrew's, Func<T, string>, .

public void ConsumeIndexedFunction<T>(Func<string, T> something)
{
    var foo = something("bar");
    // do something with foo
}

public void TestMethod(
    Dictionary<string, object> myDictionary,
    DataTable myDataTable,
    IDataReader myDataReader)
{
    ConsumeIndexedFunction(x => myDictionary[x]);
    ConsumeIndexedFunction(x => myDataTable.Rows[0][x]);
    ConsumeIndexedFunction(x => myDataReader[x]);
}

( , . !)

+6

:

interface IFoo
{
    String this[Int32 index] { get; set; }
}

, , , IFoo, , .

+5

If you cannot make all the objects (or classes accordingly), you like to pass to the mapper implementation an interface that defines such an index, you will need to use reflection.

0
source

Will the interface help in this case:

interface IImplementMe {
    string this[int index]
    {
        get;
        set;
    }
}

Just ask the parameter to implement the interface

0
source

Source: https://habr.com/ru/post/1711664/


All Articles