我正在構建一個應用程序,其中數據模型是固定的,但人們(或者我)可以通過添加從基類繼承的類來擴展它,該類從信息中實例化數據庫和序列化的服務。爲某些字段值和其他擴展點添加處理程序
我有三個問題領域與此(案例1 2和3在下面的示例代碼)。案例#1我也許可以通過一個界面來解決,但這並不能幫助我處理案例2或3.
我認爲代碼示例會說得比我嘗試解釋的要好;任何想法如何解決這個問題,以便每個新的字段類型不需要手動添加到代碼中的一堆地方?
public class ManagerClass
{
public ManagerClass()
{
public ManagerClass()
{
}
//Case #1
public void process(AllFields allFields)
{
foreach (Field field in allFields.Fields)
{
//Currently I need to add all extention types as seperate cases here manually
//...this type of logic appears in several places in the code
if (field.GetType().Name == "ExtendedField")
{
//Have the extended field do something in a way particular to it
}
else
{
//Have the base field do something the "normal" way
}
}
}
//Case #2
//Here is another case where currently I am adding each case in by hand
//fieldType is a string here because I am storing what type of field it is in the DB
public void create(string value, string fieldType)
{
//Currently I need to add all extention types as seperate cases here manually
if (fieldType == "ExtendedField")
{
//Create a ExtendedField
}
else
{
//Create a Field
}
}
}
}
[DataContract]
//Case #3
[KnownType(typeof(ExtendedField))] //Currently I need to add all extention types here manually
public class AllFields
{
private List<Field> fields;
public AllFields(){}
[DataMember]
public List<Field> Fields
{
get { return fields; }
set { fields = value; }
}
}
[DataContract]
public class Field
{
private string fieldValue;
public Field(){}
[DataMember]
public string FieldValue
{
get { return fieldValue; }
set { fieldValue = value; }
}
}
[DataContract]
public class ExtendedField : Field
{
private string someOtherAttribute;
public ExtendedField(){}
[DataMember]
public string SomeOtherAttribute
{
get { return someOtherAttribute; }
set { someOtherAttribute = value; }
}
}
我發現我也可以通過配置文件,這對我來說工作正常序列化部分添加已知類型,以及:http://msdn.microsoft.com/en-us /library/ms730167.aspx – Amasuriel