Skip to main content
 首页 » 编程设计

c#之在类中轻松初始化字符串数组

2024年02月20日23xing901022

如果一个类只包含字符串数组变量,是否有一种简单的方法可以将它们全部初始化,而不必一遍又一遍地键入相同的代码?

例如,如果我有类似的东西

[Serializable] 
public class ReadDiagnosticEntirePointValuesResponse 
{ 
    public string[] pointidentifier; 
    public string[] presentvalue; 
    public string[] priorityarray; 
    public string[] alarmstate; 
    public string[] outofservice; 
    public string[] correctvalue; 
    public string[] affect; 
    public string[] covenable; 
    public string[] covincrement; 
    public string[] covtarget; 
    public string[] covlifetime; 
    public string[] historyenable; 
    public string[] historyincrement; 
    public string[] elapsedactivetime; 
    public string[] feedbackvalue; 
    public string[] rawvalue; 
    ...//A lot more  
} 

我想给它们赋值,我想避免做:

        ReadDiagnosticEntirePointValuesResponse response = new ReadDiagnosticEntirePointValuesResponse(); 
 
 
        response.affect = new string[count]; 
        response.alarmstate = new string[count]; 
        response.correctvalue = new string[count]; 
        response.covenable = new string[count]; 
        response.covincrement = new string[count]; 
        response.covlifetime = new string[count]; 
        response.covtarget = new string[count]; 
        response.elapsedactivetime = new string[count]; 
        response.feedbackvalue = new string[count]; 
        response.historyenable = new string[count]; 
        response.historyincrement = new string[count]; 
        response.outofservice = new string[count]; 
        response.pointidentifier = new string[count]; 
        response.presentvalue = new string[count]; 
        response.priorityarray = new string[count]; 
        response.rawvalue = new string[count]; 
        ... 

当然,我可以在构造函数中编写这些初始化,但这仍然不能使我免于手动初始化它们。

避免这种情况的好方法是什么?

请您参考如下方法:

这是一种非常糟糕的数据管理方式,但是,像下面这样的方式可以....

foreach(var field in GetType().GetFields()) { 
    if(!field.IsStatic) field.SetValue(this, new string[count]); 
} 

但是!我强烈建议你重新考虑这个设计。更好的机制是:

class DiagnosticPoint // TODO: rename as appropriate 
{  // TODO: check these all need to be strings 
    public string Affect {get;set;} 
    public string AlarmState {get;set;} 
    ... 
    public string RawValue {get;set;} 
} 

并将其作为字段的数组:

public class ReadDiagnosticEntirePointValuesResponse 
{ 
    DiagnosticPoint[] points; 
    ... 

然后简单地初始化数组:

points = new DiagnosticPoint[count]; 

并初始化每个:

for(int i = 0 ; i < count ; i++) points[i] = new DiagnosticPoint(); 

并通过以下方式访问:

var alarm = points[index].AlarmState; 

(等)