使用Object Initializer拆分和连接字符串的简单方法



下面有没有缩短这段代码的方法。(期望值超过20)
这些值将始终保持相同的顺序。

string[] values = line.Split(',');
LogEntry entry = new LogEntry()
{
    Id = values[0],
    Service = values[1],
    Name = values[2],
    Process = values[3],
    type = values[4]
    [...]
};

我个人不知道有什么简化的方法可以做到这一点——这段代码需要存在于某个地方。但是,您可以使用像AutoMapper这样的映射器解决方案来设置映射。至少在这一点上,您的处理程序或操作不会因分配逻辑而膨胀。

希望这能有所帮助。

期待阅读其他答案。

您可以使用一个参数string line添加到LogEntry构造函数,并将逻辑移动到构造函数中。

然后代码将看起来像

LogEntry entry = new LogEntry(line);    

在构造函数中,类似这样的东西:

public void LogEntry(string line)
{
    string[] values = line.Split(',');
    Id = values[0],
    Service = values[1],
    Name = values[2],
    Process = values[3],
    type = values[4]
    [...]    
}

这个代码一定在某个地方。更好的解决方案取决于情况。如果您经常使用对象初始值设定项,这将大大简化代码。如果你不这样做,那可能没有太大区别。

从你的问题中,你试图避免设置值的那二十行。使用下面这样的基于反射的解决方案怎么样?

string[] values = line.Split(',');
var orderedLogEntryPropertyNames = 
new string[]{ "Id", "Name", "Process" }; 
//list all the LogEntry property names in the order that map to the values
var logEntry = new LogEntry();
var logEntryProperties = typeof(LogEntry).GetProperties();
for (int i = 0; i < values.Length; i++)
  {
    var propertyToSet = 
    logEntryProperties.First(p => p.Name.Equals(orderedLogEntryPropertyNames[i]));
    propertyToSet.SetValue(logEntry, values[i]);
   }

最新更新