Can properties inside an object initializer reference each other?

前端 未结 3 1665
广开言路
广开言路 2020-12-17 10:57

Is it somehow possible for properties to reference each other during the creation of a dynamic object an anonymously-typed object (i.e. inside the object in

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 11:27

    What you want is not possible within object intializers. You cannot read properties of the object being initialized. (It does not matter, whether the type is anonymous or not.)

    Instead, Create a class

    public class Profile
    {
        public Profile(int id)
        {
            Age = GetAgeFromSomewhere(id);
        }
    
        public int Age { get; private set; }
        public int IsLegal { get { return Age > 18; } }
    }
    

    Or getting the age the lazy way:

    public class Profile
    {
        private readonly int _id;
    
        public Profile(int id)
        {
            _id = id;
        }
    
        private int? _age;
        public int Age {
            get {
                if (_age == null) {
                    _age = GetAgeFromSomewhere(_id);
                }
                return _age.Value;
            }
        }
    
        public int IsLegal { get { return Age > 18; } }
    }
    

    or using the Lazy class (starting with Framework 4.0):

    public class Profile
    {
        public Profile(int id)
        {
           // C# captures the `id` in a closure.
            _lazyAge = new Lazy(
                () => GetAgeFromSomewhere(id)
            );
        }
    
        private Lazy _lazyAge;
        public int Age { get { return _lazyAge.Value; } }
    
        public int IsLegal { get { return Age > 18; } }
    }
    

    Call it like this

    var profile = new Profile(id);
    

提交回复
热议问题