[英]Expose a field from a Class and add a property?
I have a silly problem and I am possibly going about this the wrong way. 我有一个愚蠢的问题,我可能会以错误的方式解决。
I want to add a property to a class to change a field. 我想向类添加属性以更改字段。 I am thinking that this is not possible due to the Class level of protection. 我认为由于Class等级的保护,这是不可能的。
SEE: Microsoft.SPOT.Hardware.PWM I want my code to modify this Class. 请参阅: Microsoft.SPOT.Hardware.PWM我希望我的代码修改此类。
I want to change the Boolean: 我想更改布尔值:
bool invert;
in the initialisation of the Class: 在类的初始化中:
PWM pwm = new PWM(Cpu.PWMChannel.PWM_4, 10, 0.5, true);
I want to be able to access the true variable and modify it. 我希望能够访问true变量并对其进行修改。 At will that is outside of creating a new instance. 随意创建新实例之外。
I have tried: 我努力了:
public partial class PWM : Microsoft.SPOT.Hardware.PWM
{
private static bool invert;
protected static bool Invert
{
get { return invert; }
set { invert = value; }
}
}
I think this is a failure anyone have any ideas to expose this as a property? 我认为这是失败的,任何人都没有任何想法将此属性公开为财产?
protected
modifier means that field can be accessed only from within the class or it's children. protected
修饰符意味着只能在班级或其子级中访问该字段。
If you want to expose the field, use public: 如果要公开该字段,请使用public:
private static bool _invert;
public static bool Invert{
get { return _invert; }
set { _invert = value; }
}
}
Your question is not very clear - are you asking how to make a class field visible outside the class? 您的问题不是很清楚-您是否在问如何使班级字段在班级之外可见?
If so, you can either expose it via a property as you have already done: 如果是这样,您可以像已经完成的那样通过属性公开它:
public static int PropertyName
{
get
{
return this._PropertyName;
}
set
{
this._PropertyName = value;
}
}
/// <summary>
/// privatefield for PropertyName
/// </summary>
private static int _PropertyName;
Or you can simply declare the field as public. 或者,您可以简单地将该字段声明为公共字段。 I would always go with the property so I can control what values and under what conditions the value can be set. 我将始终使用该属性,以便可以控制哪些值以及在什么条件下可以设置该值。
Alternative to base class: 替代基类:
public Microsoft.SPOT.Hardware.PWM PWM {get;set;}
public bool PwmBool
{
get
{
return false;
}
set
{
this.PWM = new PWM(Cpu.PWMChannel.PWM_4, 10, 0.5, value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.