我对C#还是很陌生,这很可能是我的方法完全不适合...我正在尝试建立一个类,该类是另一个类型的容器,该类型可以在派生类中扩展。 基本上,我当前的代码如下所示:
public class BaseFormFields
{
public String baseFieldName1 {get; set;}
}
public abstract class BaseOrder<F> where F : BaseFormFields
{
public String orderProperty1 {get; set;}
public F formFields { get; set; }
}
在派生类中
public class SpecificFormFields : BaseFormFields
{
public String specificFieldNam1 {get; set;}
}
public class SpecificOrder : BaseOrder<SpecificFormFields>
{
}
虽然这基本上可以工作,但我如何需要在BaseFormFields或SpecificFormFields类中构造一个方法来从BaseOrder访问成员?我尝试过:
public class BaseFormFields
{
public string BaseFieldName1 { get; set; }
public Object _order;
public BaseOrder<BaseFormFields> order
{
get
{
return (BaseOrder<BaseFormFields>)_order;
}
}
}
public abstract class BaseOrder<F> where F : BaseFormFields
{
public String orderProperty1 { get; set; }
private F _formFields;
public F formFields
{
get
{
return _formFields;
}
set
{
value._order = this;
_formFields = value;
}
}
}
public class SpecificFormFields : BaseFormFields
{
public String SpecificFieldName1 { get; set; }
public String SpecificFieldName2
{
get
{
return order.orderProperty1;
}
}
}
public class SpecificOrder : BaseOrder<SpecificFormFields>
{
}
可以编译,但是在尝试执行操作时却给出了InvalidCastException
SpecificOrder specificOrder = new SpecificOrder();
specificOrder.orderProperty1 = "Test";
specificOrder.formFields = new SpecificFormFields();
String s = specificOrder.formFields.SpecificFieldName2;
感谢您的帮助...