C# 检查字符串类型的类成员的值,该类成员只能假定几个值
我通过对XML模式文件运行xsd/c创建了以下分部类:C# 检查字符串类型的类成员的值,该类成员只能假定几个值,c#,partial,C#,Partial,我通过对XML模式文件运行xsd/c创建了以下分部类: [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [Sys
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="example.com")]
public partial class FRUITQueryType {
private string fruitTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string FruitType {
get {
return this.fruitTypeField;
}
set {
this.fruitTypeField = value;
}
}
}
但是,由于该字段只有几个可能的值,因此这种方法感觉不整洁。
我认为如果我能沿着以下几行检查字段的值会更好:
if (fruit.FruitType == FRUITQueryType.FruitType.Banana) // or something similar
实现这一点有意义吗?
如果是,最好的方法是什么?通过创建一个包含三个静态成员的类/结构,其中包含Banana、Orange和Blueberry?我想出了一个临时解决方案——虽然不理想,但可以做到这一点 我在扩展类中将这三个字符串定义为常量:
public partial class FRUITQueryType
{
public const string Banana = "Banana";
public const string Orange = "Orange";
public const string Blueberry = "Blueberry";
// ...
}
这样,支票将变为:
if (fruit.FruitType == FRUITQueryType.Banana)
我必须说,我对这个解决方案并不完全满意,因为它让全班感到混乱。
但是,如果我在一个子类/结构中定义了常量,比如说,public struct FruitChoice,那么如果fruit.FruitType==FRUITQueryType.FruitChoice.Banana,检查也会变得更麻烦
有人想出了一个更整洁的方法吗?you可能想看看,如果你被蹩脚的xsd困住了,你能做的不多。查看一般建议。@astander我考虑过枚举,但如何检查水果类型a字符串的内容是否等于水果枚举。香蕉?@HansPassant应该这样做。不幸的是,我不能修改原来的xsd.Hmya,我看到了。。。
if (fruit.FruitType == FRUITQueryType.Banana)