WCF新手寻求帮助。我在这里做错了什么: ICardService
[ServiceContract(Namespace = "http://xxxx.xxxxxx.xxxx/xx/xxxxxx")]
interface ICardService
{
[OperationContract]
Coupon CreateCouponCard(string cardDefinitionCode);
}
public class CardService : ICardService
{
public Coupon CreateCouponCard(string cardDefinitionCode)
{
Coupon composite = new Coupon();
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.PassTypeIdentifier="sdfsdf";
composite.Icon.DisplayGroup = "czxczxczx";
}
return composite;
}
}
[DataContract(Namespace = "")]
public class Coupon : CardCommonDefinition
{
[DataMember]
public string Description {get; set;}
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
}
[DataContract(Namespace = "")]
public class CardCommonDefinition
{
[DataMember]
public string PassTypeIdentifier {get; set;}
[DataMember]
public CardFieldDefinitionEntity Icon {get; set;}
}
[DataContract(Namespace = "")]
public class CardFieldDefinitionEntity
{
[DataMember]
public string DisplayGroup {get; set;}
}
当我运行它时,它在composite.Icon.DisplayGroup =“czxczxczx”失败了;对象未设置为对象的实例。
我没有任何线索要解决它,你能帮助我吗?
答案 0 :(得分:2)
你可以通过两种方式解决这个问题。
One-在使用之前初始化Icon
属性。
public Coupon CreateCouponCard(string cardDefinitionCode)
{
Coupon composite = new Coupon();
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.PassTypeIdentifier="sdfsdf";
composite.Icon = new CardFieldDefinitionEntity();
composite.Icon.DisplayGroup = "czxczxczx";
}
return composite;
}
两个 - 拥有CardCommonDefinition
的构造函数并初始化Icon
属性,这样您就不必担心它是null。
[DataContract(Namespace = "")]
public class CardCommonDefinition
{
public CardCommonDefinition()
{
this.Icon = new CardFieldDefinitionEntity();
}
[DataMember]
public string PassTypeIdentifier {get; set;}
[DataMember]
public CardFieldDefinitionEntity Icon {get; set;}
}
[DataContract(Namespace = "")]
public class Coupon : CardCommonDefinition
{
public Coupon : base()
{ }
[DataMember]
public string Description {get; set;}
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
}