,并且我将需要其中任何一个由创建此类对象的人填充;在C#中有没有可以强加这种行为的方法?如果在一个类中有两个公共属性,那么这两个属性中的任何一个都将被赋值
所以,基本上如果Property1已经被赋予了一个值,那么用户不应该给Property2一个值,或者反之呢?
如果不是,是否有任何最佳做法来做到这一点,而不是创建2个单独的类,Property1在一个类中,Property2在第二个类中?
或者可能是一个方法属性,可以通知用户这种行为?那会有用吗?
,并且我将需要其中任何一个由创建此类对象的人填充;在C#中有没有可以强加这种行为的方法?如果在一个类中有两个公共属性,那么这两个属性中的任何一个都将被赋值
所以,基本上如果Property1已经被赋予了一个值,那么用户不应该给Property2一个值,或者反之呢?
如果不是,是否有任何最佳做法来做到这一点,而不是创建2个单独的类,Property1在一个类中,Property2在第二个类中?
或者可能是一个方法属性,可以通知用户这种行为?那会有用吗?
您可以在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; }}
}
您可以将逻辑放置在属性设置器中,以便在设置其他属性时清除其中一个属性。
只需将代码强制执行到每个属性的设置器,你就完成了。例如:
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;
}
}
}
输出:因为STR1的设置第一STR2的值永远不会设置,并且因此打印一个空字符串
Hello
的通知。
谢谢...但我只能选择1个回答....(所有三个是答案...) – user402186 2011-04-13 18:20:07
对于两个属性,我可能会做像其他答案一样的setters检查。但你可以做这样的事情...
而不是使它两个属性,也许他们应该是一个。人为的例子:想象一下,而不是有地址属性UsaZipCode(int)和CanadianPostalCode(串),它有一个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; }
}
现在解决不能同时拥有美国和加拿大邮政编码。额外的复杂性值得吗?取决于用例。
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;
}
}
}
谢谢...但我只能选择1个回答....(三者的答案...) – user402186 2011-04-13 18:18:46