简体   繁体   中英

Generic way to access class properties

I have been trying to read the value from the excel sheet, map it into a dataTable and then map the value to its class in C# using reflection. There is no issue for this

I have two classes- one providing test data, and another one providing the logic to read a fixed-width file.

When the two classes have more properties, the way i access to its properties somehow duplicating.

Here is the TestData class

class TestData
{
     public string TestName { get; set; }
     public string Name{ get; set; }
     public string Address{ get; set; }
}

//ignoring the whole logic in the middle, i can access the value of the test by
_testData.Name or _testData.Address

Here is the class to access fixed-width file


class FieldPosition
{
     public string FieldName { get; set; }
     public string PosStart{ get; set; }
     public string PosEnd{ get; set; }
}

class IncomingFields
{
     public FieldPosition Name => GetValue("Name");
     public FieldPosition Address=> GetValue("Address");
}
//ignoring the whole logic in the middle, i can access the value of the field position by
_field.Name.PosStart or _field.Name.PosEnd

When TestData and IncomingFields have more properties, the code to call them becomes a big duplicating mess. Is there any way to reduce the code since the property name is the same?

Here is what i have to do per one property.

if (_testData.Name != "")
{
    ModifyFixedWidthFile(_testData.Name, _field.Name.PosStart, _field.Name.PosEnd)
}

if (_testData.Address!= "")
{
    ModifyFixedWidthFile(_testData.Address, _field.Address.PosStart, _field.Address.PosEnd)
}

Is there anyway to reduce 2 if conditions, into 1 block of code by doing a foreach loop? I just don't know how to call the properties in a generic way. is it possible to do something like this in c#

if (_testData.[something generic]!= "")
{
    ModifyFixedWidthFile(_testData.[something generic], _field.[something generic].PosStart, _field.[something generic].PosEnd)
}

My names for methods and arguments are all close to useless here.

void OuterMethod(TestData testData, IncomingFields fields)
{
    ModifySomething(testData.Address, fields.Address);
    ModifySomething(testData.Name, fields.Name);
}

void ModifySomething(string value, FieldPosition fieldPosition)
{
    if (value != "")
        ModifyFixedWithFile(value, fieldPosition.PosStart, fieldPosition.PosEnd);
}

This just breaks it into two functions. The outer method selects a string property from testData and selects a FieldPosition property from fields . Those are the only parts that are changing. Then it calls the inner ModifySomething method which acts on those values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM