如何将非静态枚举值与 DefaultValue 数据注释一起使用?
public enum ProductQuantityType {
Weight = 1,
Volume = 2,
Custom = 0
}
失败
[MetadataType(typeof(ProductMetaData))]
public partial class Product {
public class ProductMetaData {
[DefaultValue(ProductQuantityType.Weight)]
public object QuantityType { get; set; }
}
}
错误:非静态字段、方法或属性需要对象引用
public enum ProductQuantityType {
Weight = 1,
Volume = 2,
Custom = 0
}
This fails
[MetadataType(typeof(ProductMetaData))]
public partial class Product {
public class ProductMetaData {
[DefaultValue(ProductQuantityType.Weight)]
public object QuantityType { get; set; }
}
}
Error: An object reference is required for the non-static field, method, or property
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测,这可能是因为您的 QuantityType 字段是一个
object
(引用类型),但您的枚举是一个值类型。显然,您应该将该 auto-impl-prop 设置为int
或ProductQuantityType
。您知道当您实例化新的 ProductMetadata 时 DefaultValue 不会设置此字段吗?如果您希望它始终具有初始值,则应该在构造函数中设置它。
My guess, this is probably because your QuantityType field is an
object
(reference type), but your enum is a value type. You should obviously be making that auto-impl-prop either anint
, or aProductQuantityType
.You are aware that DefaultValue is not going to set this field when you instantiate a new ProductMetadata right? If you want it to always have an initial value, you should be setting it in the constructor.