在实例化时通过条件将项目取消



我有这个类

public class Item
{
    public int Prop1 { get; set; }
    public Item(string value)
    {
        int temp;
        if (int.TryParse(value, out temp))
        {
            Prop1 = temp;
        }
        else
        {
            this = null;
        }
    }
}

但是this = null;不编译。有可能做出这种行为吗?

Item foo = new Item("x"); //foo == null because "x" can't be parsed into int

您可以创建静态方法来创建项目:

public class Item
{
    public int Prop1 { get; set; }
    public Item(int value)
    {
        Prop1 = value;
    }
    public static Item Create(string value)
    {
        int i;
        return int.TryParse(value, out i) ? new Item(i) : null;
    }
}

您可以打电话

Item foo = Item.Create("x");

如果您不希望用户使用INT参数创建项目,而不是将构造函数私有。这种方式item.Create(字符串值(将是用户创建项目实例的唯一方法。

不,你不能。this参考声明该属性的类实例,您不能使其自身无效。如果您确实需要该支柱具有一个值,请创建一个带有参数的构造函数,请检查值分析到int(为什么不能是int(,并在不

的情况下抛出异常
public class Item
{
   public Item(string x){
    if (!int.TryParse(value, out temp))
        {
            throw new ArgumentException("Give me an int to parse");
        }
        else
        {
            Prop1 = temp;
        }
     }
}

no,您不能在该实例中将实例设置为null。

更好的选择可能是拥有另一个属性(或方法(,以指示您的类实例的有效性

public class Item
{
    public int Prop1 { get; set; }
    public bool IsValid{ get; set; }
    public Item(string value)
    {
        int temp;
        if (int.TryParse(value, out temp))
        {
            Prop1 = temp;
            IsValid = true;
        }
        else
        {
            IsValid = false;
        }
    }
}

但是this = null;不编译。有可能做出这种行为吗?

不,您不能从班级内部做到这一点。但是,您可以从那里设置任何属性。例如你可以做

public int? Prop1 { get; set; }

和做

Prop1 = null;

最新更新