要为其分配值的任一属性

时间:2011-04-13 17:53:32

标签: c#

如果一个类中有两个公共属性,我将需要由创建该类对象的人填充其中任何一个;在C#中是否存在可以强加此行为的方法?

所以基本上如果给Property1一个值,那么用户不应该给Property2一个值,反之亦然?

如果不是,有没有最好的做法,而不是创建2个单独的类,一个类中的Property1和第二个类中的Property2?

或者可能是可以通知用户此行为的方法属性?那会有用吗?

5 个答案:

答案 0 :(得分:4)

您可以在属性设置器中放置逻辑,以便在设置另一个属性时清除一个属性。

答案 1 :(得分:1)

只需将代码强制执行约束到每个属性的setter中即可。例如:

using System;

public class MyClass {
    public static void Main()   { 
        TestClass tc = new TestClass();
        tc.Str1 = "Hello";
        tc.Str2 = "World!"; // will not be set because of enforced constraint
        Console.WriteLine(tc.Str1);
        Console.WriteLine(tc.Str2);
        Console.ReadKey();
    }
}

public class TestClass {
    private string _str1;
    public string Str1  {
        get { return _str1; }
        set {
            if (string.IsNullOrEmpty(Str2))
                _str1 = value;
        }
    }

    private string _str2;
    public string Str2  {
        get { return _str2; }
        set {
            if (string.IsNullOrEmpty(Str1))
                _str2 = value;
        }
    }
}

输出:

Hello

请注意,Str2的值永远不会设置,因为首先设置了Str1,因此会打印一个空字符串。

答案 2 :(得分:1)

您可以在setter中添加代码。有点像这样......

public class MyClass 
{
int one = -1;
int two = -2;

public int One { get { return this.one; }
                 set { if (this.two != -1 ) this.one == value; }}

public int Two { get { return this.two; }
                 set { if (this.one!= -1 ) this.two== value; }}
}

答案 3 :(得分:0)

对于两个属性,我可能会像其他答案一样进行setter检查。但你可以这样做......

可能它们应该是一个,而不是使它成为两个属性。 Contrived Example:想象一下,而不是具有属性UsaZipCode(int)和CanadianPostalCode(string)的地址,它有一个像这样的PostalCode:

class Address
{
    public string Street { get; set; }
    public IPostalCode PostalCode { get; set;}
}

public interface IPostalCode
{
    int? Usa { get; }
    string Canadian { get; }
}

public class UsaPostalCode
{
    private int _code;
    public UsaPostalCode(int code) { _code = code; }
    public int? Usa { get { return _code; }
    public string Canadian { get { return null; }
}

public class CanadianPostalCode
{
    private string _code;
    public CanadianPostalCode(string code) { _code = code; }
    public int? Usa { get { return null; }
    public string Canadian { get { return _code; }
}

现在地址永远不会有美国和加拿大的邮政编码。额外的复杂性值得吗?取决于用例。

答案 4 :(得分:0)

public class MyClass
{
    private string pickedProperty = null;
    private object member1;
    private object member2;

    public object Property1 
    {
        get { return this.member1; }
        set 
        {
            if (this.pickedProperty == null)
                this.pickedProperty = "Property1";

            if (this.pickedProperty == "Property1")
                this.member1 = value;
        }
    }

    public object Property2 
    {
        get { return this.member2; }
        set
        {
            if (this.pickedProperty == null)
                this.pickedProperty = "Property2";

            if (this.pickedProperty == "Property2")
                this.member1 = value;
        }
    }
}