我有一个基类ProductDetails负责解析产品字符串,还有另一个类SelfManufactured,它从基类ProductDetails继承,还有另一个类-ThirdPartyProduct,它继承了SelfManufactured类,并且具有其他特定于此类,例如ThirdPartyName,ThirdPartyAddress。
a)对于SelfManufactured产品,字符串应为-前缀为0
b)对于ThirdPartyProduct产品,字符串应为-前缀为1
工作流程如下:
我使用以下代码创建ThirdPartyProduct对象:
private void ThirdParty_Click(object sender, RoutedEventArgs e)
{
ThirdPartyProduct thirdparty = new ThirdPartyProduct ("1000", "200", "PROD1",
"XYZW", "ABCD");
string thirdpartyProductString = thirdparty.ToString();
}
如果在下面的代码中检查变量thirdpartyProductString,则为:先附加0,再附加1。 它附加0,然后附加1,而我希望只有前缀“ 1”。 我猜想,由于在创建ThirdParty对象时也会调用SelfManufactured类,因此它会继续附加值,我想有一种方法,使ToString()在不需要时不附加值。
ProductDetails.cs
using System;
namespace product
{
public class ProductDetails
{
private readonly string _productString;
public string ProductString
{
get => ToString();
}
public ProductDetails(string productId, string productName, string productLot)
{
_productString = // somevalue here....
}
public override string MyString()
{
return _productString;
}
}
}
SelfManufactured.cs
public class SelfManufactured : ProductDetails
{
public override string MyString()
{
string str = string.Empty;
str = "additional value of 0" + // append the identifier as '0' with product string
return str;
}
}
ThirdPartyProduct.cs
public class ThirdPartyProduct : SelfManufactured
{
public string ThirdPartyName { get; set; }
public string ThirdPartyAddress { get; set; }
public override string MyString()
{
string str = string.Empty;
// append the identifier as '1' with product string and add additional details with the string.
return str;
}
}
答案 0 :(得分:0)
由于您正在“ ThirdPartyProduct”类中调用base.ToString(),因此它显然会调用基类ToString()方法,并向其添加“ 0”,并将最终字符串作为“ 101000200PROD1XYZWABCD”
如果您不想这样做,则可以直接从ThirdPartyProduct类的ToString()方法引用ProductDetails类的“ ProductString”属性。见下文我的更改
ProductDetails.cs -我从此处返回私有只读文件。
public string ProductString
{
get { return _productString; }
}
然后对以下更改进行ThirdPartyProduct.cs类的ToString()方法
public override string ToString()
{
string str = string.Empty;
// append the identifier as '0' with product string and add additional details with the string.
str = (int)ProductType.ThirdParty + ProductString + ThirdPartyName + ThirdPartyAddress;
return str;
}
在以下行进行了更改-
str =(int)ProductType.ThirdParty + base.ToString() + ThirdPartyName + ThirdPartyAddress;
到
str =(int)ProductType.ThirdParty + ProductString + ThirdPartyName + ThirdPartyAddress;
注意:-我希望始终ThirdPartyProduct类不应该附加“ 0”,那么上面的解决方案应该可以,否则您需要考虑其他方法进行计算。
答案 1 :(得分:0)
您已经在ProductDetails类中拥有一个称为“ TypeOfProduct”的属性。因此,在SelfManufactured.ToString()中,而不是对产品类型进行硬编码,请使用属性的值:
str = (int)TypeOfProduct + base.ToString();
然后,在ThirdPartyProduct中,无需使用产品类型,因为在基本类中已对此进行了处理。因此,请改为调用base.ToString(),后跟特定于类的详细信息:
str = base.ToString() + ThirdPartyName + ThirdPartyAddress;