我正在創建一個日誌分析工具,即將CSV文件解析爲從根類派生的各個類。但是,定義各個類並在每個類中設置其各自的屬性需要很長時間,因爲有數百種不同類型的日誌。我注意到的事情是,這幾乎都是完全相同的東西,並想看看是否有辦法加快速度,並按照LINQ to DB如何操作並添加一些邏輯來自動設置基於來自Attributes的信息的屬性。在父類中使用自定義屬性設置子項屬性
下面是我正在使用的一個示例,以及關於應該如何工作的一個想法。
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>
{
{"key", "Stack Overflow"},
{"item1", "Test"},
{"item2", "Sample"},
{"item3", "3"}
};
Example example = new Example(dictionary);
Console.WriteLine(example.LogKey); //Stack Overflow
Console.WriteLine(example.Item1); //Test
Console.WriteLine(example.Item2); //
Console.WriteLine(example.Item3); //3
Console.ReadKey();
}
}
[AttributeUsage(AttributeTargets.Property)]
class LogItem : Attribute
{
public LogItem(string key)
{
Key = key;
}
public string Key { get; private set; }
public bool Ignore { get; set; }
}
class Log
{
public Log(Dictionary<string, string> items)
{
Dictionary = items;
}
public Dictionary<string, string> Dictionary { get; private set; }
[LogItem("key")]
public string LogKey { get; set; }
}
class Example : Log
{
public Example(Dictionary<string, string> items) : base(items)
{
}
[LogItem("item1")]
public string Item1 { get; set; }
[LogItem("item2", Ignore = true)]
public string Item2 { get; set; }
[LogItem("item3")]
public int Item3 { get; set; }
}
我所有的數據將作爲字符串通過正在添加不幸所以這將是一個好主意,讓該屬性的類型和字符串轉換爲這一點。這個問題現在並不重要,因爲我可以自己做到這一點。
有沒有人有關於如何做這種工作的想法?如果可能的話,可以在父類中完成這樣的事情,以允許子類自己設置屬性Ignore == true
。
你可以使用反射來設置屬性,但是如果你已經有'Dictionary',爲什麼你真的需要屬性? 'Example'類的用法是什麼?爲什麼不保留'Dictionary'?而且,對於屬性來說,它並不是很清楚(對我?)。 CSV - >字典,完美,無需上課。 – Sinatr