C# 如何在属性上使用条件语句IF-ELSE
我想基于MyPropertySelected显示MyProperty1或MyProperty2。如果或基于MyPropertySelected,如何使用条件语句?谢谢C# 如何在属性上使用条件语句IF-ELSE,c#,winforms,properties,attributes,conditional-operator,C#,Winforms,Properties,Attributes,Conditional Operator,我想基于MyPropertySelected显示MyProperty1或MyProperty2。如果或基于MyPropertySelected,如何使用条件语句?谢谢 您可能需要这样的中间属性: class Foo { public bool MyPropertySelected { get; set; } public readonly int MyProperty { get {
您可能需要这样的中间属性:
class Foo
{
public bool MyPropertySelected
{
get;
set;
}
public readonly int MyProperty
{
get
{
return MyPropertySelected ? MyProperty1 : MyProperty2;
}
}
private int MyProperty1
{
get;
set;
}
private int MyProperty2
{
get;
set;
}
}
你把苹果和桔子搞混了 属性是元数据,属性值在运行时获取其值 换句话说:属性是您将使用访问的对象,这些属性不绑定到特定对象,而是绑定到对象的类型,即类 另一个问题是,您希望根据编译时无法工作的条件向属性添加属性 MyPropertySelected在其封闭类实例化之前不会获得任何值,这将创建一个对象,例如:MyClass a=new MyClass-,这意味着添加或不添加属性将永远不是编译时的选择 我想明确一点:你不能仅仅使用属性来做你想做的事情 不能基于运行时值有条件地应用属性 最后,我怀疑您希望根据条件使某些内容可浏览,就像您自己的问题所说的那样。你不能那样做 好吧,但是什么。。。? 您可以使用不同的软件设计来解决您的情况 1. 首先,创建一个接口,该接口将具有可浏览或不可浏览的任何属性。但不要将属性[Browsablebool]应用于接口属性 2. 创建两个实现先前创建的接口的类 在第一个类中,实现接口属性并在其上放置[Browsabletrue]属性。在第二节课中,也要这样做,但这次在他们身上放一个[Browsablefalse] 3. 一些创建对象实例的代码也将决定实例化哪个实例 也就是说,将MyPropertySelected外部化到两个类之外,并在调用者中执行整个条件切换
public interface IBrowsableProperties
{
int Property1 { get;set; }
int Property2 { get;set; }
}
public class A : IBrowsableProperties
{
[Browsable(true)]
public int Property1 { get;set; }
[Browsable(true)]
public int Property1 { get;set; }
}
public class B : IBrowsableProperties
{
[Browsable(false)]
public int Property1 { get;set; }
[Browsable(false)]
public int Property1 { get;set; }
}
// Somewhere in some method...
bool propertySelected = true;
IBrowsableProperties instance = null;
if(propertySelected)
{
instance = new A();
}
else
{
instance = new B();
}
// ... do stuff with your instance of IBrowsableProperties!
使现代化
我查看了您的一些问题评论,发现您正在使用PropertyGrid控件
无论如何,你可以在你的案例中应用这个概念。PropertyGrid可以被继承。您可以创建PropertyGrid1和PropertyGrid2派生类,它们都实现了建议的接口 现在还不清楚,您希望如何使用属性……我希望使用以下条件将上述属性绑定到属性网格:MyPropertySelected always Browsabletrue。如果我在属性网格中将MyPropertySelected值选择为true,MyProperty1将被设置为Browsabletrue,MyProperty2将被设置为MyProperty2将被设置为Browsablefalse。@YD4没问题!不客气。在我的答案底部查看我的更新,这应该是一个很好的提示:@KonstantinVasilcov谢谢!我得到了灵感:D
public interface IBrowsableProperties
{
int Property1 { get;set; }
int Property2 { get;set; }
}
public class A : IBrowsableProperties
{
[Browsable(true)]
public int Property1 { get;set; }
[Browsable(true)]
public int Property1 { get;set; }
}
public class B : IBrowsableProperties
{
[Browsable(false)]
public int Property1 { get;set; }
[Browsable(false)]
public int Property1 { get;set; }
}
// Somewhere in some method...
bool propertySelected = true;
IBrowsableProperties instance = null;
if(propertySelected)
{
instance = new A();
}
else
{
instance = new B();
}
// ... do stuff with your instance of IBrowsableProperties!