c# - 在类验证代码中创建还是创建验证类?

标签 c# oop exception

这是我的第一篇文章,所以我对一些错误提前表示歉意,而且英语不是我的母语。 什么更好,为什么?请记住,我正在与另外 2 个人一起工作,我们将有 4 个类来代表不同类型的人,每个类将具有大约 15 个属性。

A - 为同一类中类的每个属性创建验证:

public class People
{
    string name { get; set; }

    private void ValidateName()
    {
        if(this.name.Contains("0", ..., "9"))
            throw new Exception("Name can't contain numbers.");
    }
}

或 B - 创建一个类(也许是静态类?)仅用于验证:

public class People
{
    string name { get; set; }
}

static class Validation
{
    static void Name(string name)
    {
        if(name.Contains("0", ..., "9"))
            throw new Exception("Name can't contain numbers.")
    }
}

//and then somewhere in the code I call the Validation.Name(name) to verify if the code is ok.

还有第三种更合适的选择吗?我什至不知道使用异常是否是正确的方法。

提前谢谢您!

最佳答案

您可以使用您的方法在构造函数中实例化时引发错误,如下所示

public class People
    {
        string name { get; set; }

        public People(string n)
        {
            if (ValidateName(n))
            {
                this.name = n;
            }
        }

        private bool ValidateName(string n)
        {
            char[] nums = "0123456789".ToCharArray();
            if (n.IndexOfAny(nums) >= 0)
            {
                throw new Exception("Name can't contain numbers.");
            }
            return true;
        }
    }

使用上面的代码,下面的代码将抛出异常。

People p = new People("x1asdf");

这将是一个成功的实例化

People p = new People("xasdf");

关于c# - 在类验证代码中创建还是创建验证类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337150/

相关文章:

c# - 警告 “The type X in Y.cs conflicts with the imported type X in Z.dll”

python - 自动装饰子类中的父类(super class)函数?

java - 当我从 native Java 方法抛出 C++ 异常时会发生什么?

java - 异常和堆栈跟踪

java - 用于引发异常的内联 lambda 语法

c# - 具有 UUID (GUID) 的 MongoDB C# 过滤器返回 0 结果

c# - 网络 MVC : How do I get virtual url for the current controller/view?

python - 在动态添加的方法中调用 super 的正确方法是什么?

c# - 使用 REST 和 HTTPClient 在 SP2013 中创建文件夹

c# - 重构具有不同属性的相同循环