如何在引用前确保类有效? [英] How to make sure a class is valid before referencing?

查看:52
本文介绍了如何在引用前确保类有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    public class Person
    {
        public string FullName { get; set; }
        public int? PhoneNumber { get; set; }
        public int? CarQTY { get; set; }
    }

如果某人没有完整的对象,我想抛出一个异常填充。例如,如果fullName,phoneNumber或carQTY为null,我想在get方法上引发异常。

I want to throw an exception if someone doesn't have the object completely populated. For example, if fullName, phoneNumber, or carQTY is null, I want to throw an exception on the get method.

我真的必须这样做吗?

    public class Person
    {
        string _FullName;
        int? _PhoneNumber;
        int? _CarQTY;

        private Boolean IsValid()
        {
            Boolean condition = true;
            condition = (FullName != null) && (PhoneNumber != null) && (CarQTY != null);
            return condition;
        }
        public string FullName
        {
            get
            {
                if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "fullName is null");
                return _FullName;
            }
            set
            {
                _FullName = value;
            }
        }
        public int? PhoneNumber
        {
            get
            {
                if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "phoneNumber is null");
                return _PhoneNumber;
            }
            set
            {
                _PhoneNumber = value;
            }
        }
        public int? CarQTY
        {
            get
            {
                if (!IsValid()) throw new System.ArgumentException("Parameter cannot be null", "carQTY is null");
                return _CarQTY;
            }
            set
            {
                _CarQTY = value;
            }
        }
    }


推荐答案

如注释中所建议,强制通过构造函数创建对象只是最有效的方法:

As suggested in the comments, forcing to create the object through a constructor is simply the most efficient way:

    public class Person
    {
        public string FullName { get; private set; }
        public int PhoneNumber { get; private set; }
        public int CarQTY { get; private set; }

        public Person(string fullName, int phone, int carQty){
            FullName = fullName;
            PhoneNumber = phone;
            CarQTY = carQty;
        }
    }

如果您愿意,设置者也可能是公开的创建对象后,允许对其进行修改。

The setters might also be public, if you want to allow the modification of the object once it has been created.

这篇关于如何在引用前确保类有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆