开发者

How to use non-static enum values with the DefaultValue data annotation?

开发者 https://www.devze.com 2023-01-09 05:37 出处:网络
public enum ProductQuantityType { Weight开发者_如何学Go = 1, Volume = 2, Custom = 0 } This fails [MetadataType(typeof(ProductMetaData))]
public enum ProductQuantityType {
    Weight开发者_如何学Go = 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


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 an int, or a ProductQuantityType.

    [DefaultValue(ProductQuantityType.Weight)]
    public ProductQuantityType QuantityType { get; set; }

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消