将多个 类 转换为 sub-classes 的最佳方法
Best way to convert multiple classes to sub-classes
我正在尝试找到 create/convert 多个 class 的最简单方法,并在适当的 sub-classes.
下创建它们
下面是我的活动代码Class
public class Event
{
public Dictionary<string, string> dictionary = new Dictionary<string, string>();
public Event(string[] headers, string[] values)
{
if (headers.Length != values.Length)
throw new Exception("Length of headers does not match length of values");
for (int i = 0; i < values.Length; i++)
dictionary.Add(headers[i], values[i]);
}
public override string ToString()
{
return dictionary.ToString();
}
public string getTimeStamp()
{
return DateTime.Parse(dictionary["event_ts"]).ToLocalTime().ToString();
}
public string getKey()
{
return dictionary["hbase_key"];
}
public string getEventType()
{
return dictionary["event_type"];
}
}
除此之外,我将拥有多个 class 事件 Class 的扩展,为不同类型的事件定义更多方法。但是,我需要一种基于 EventType 的简单方法来创建正确的 class。例如,如果 event_type = testEvent,我将需要使用我的 TestEvent class。我可以在事件中放入某种方法来解析 event_type 并确定它应该创建哪个 class。
我得到的所有信息都来自解析一个 CSV 文件,其中 headers 作为第一行,值是特定行的值。
您可以使用反射将 class 类型与事件类型匹配,然后使用以下方法实例化它:
Activator.CreateInstance(eventType) as Event
您可以使用 'Factory Method'。
public Event CreateEvent(string sEventType)
{
if (sEventType.Equals("Event1"))
return new Event1();
if (sEventType.Equals("Event2"))
return new Event2();
if (sEventType.Equals("Event3"))
return new Event3();
//and so on...
}
Event1、Event2 和 Event3 是您的子类。您将需要解析和调用这种方法。
我正在尝试找到 create/convert 多个 class 的最简单方法,并在适当的 sub-classes.
下创建它们下面是我的活动代码Class
public class Event
{
public Dictionary<string, string> dictionary = new Dictionary<string, string>();
public Event(string[] headers, string[] values)
{
if (headers.Length != values.Length)
throw new Exception("Length of headers does not match length of values");
for (int i = 0; i < values.Length; i++)
dictionary.Add(headers[i], values[i]);
}
public override string ToString()
{
return dictionary.ToString();
}
public string getTimeStamp()
{
return DateTime.Parse(dictionary["event_ts"]).ToLocalTime().ToString();
}
public string getKey()
{
return dictionary["hbase_key"];
}
public string getEventType()
{
return dictionary["event_type"];
}
}
除此之外,我将拥有多个 class 事件 Class 的扩展,为不同类型的事件定义更多方法。但是,我需要一种基于 EventType 的简单方法来创建正确的 class。例如,如果 event_type = testEvent,我将需要使用我的 TestEvent class。我可以在事件中放入某种方法来解析 event_type 并确定它应该创建哪个 class。
我得到的所有信息都来自解析一个 CSV 文件,其中 headers 作为第一行,值是特定行的值。
您可以使用反射将 class 类型与事件类型匹配,然后使用以下方法实例化它:
Activator.CreateInstance(eventType) as Event
您可以使用 'Factory Method'。
public Event CreateEvent(string sEventType)
{
if (sEventType.Equals("Event1"))
return new Event1();
if (sEventType.Equals("Event2"))
return new Event2();
if (sEventType.Equals("Event3"))
return new Event3();
//and so on...
}
Event1、Event2 和 Event3 是您的子类。您将需要解析和调用这种方法。