I am fairly new to C# so be gentle.
My end goal is to have a few different types of classes for inheritance (example below: Level ). These inherited classes do two things, have .Value property with different setters depending on the class, and a .Action method, unique for every instance so it is an override.
Question: how do i set the .Value property from a method on the class. This is the line of code (line 27) that does not work from the example below. And I don't understand why.
Potentiometer.Value = Convert.ToDouble(data);
// Code taken from https://dotnetfiddle.net/YNJpjf
using System;
namespace Main {
class Program
{
static Device device = new Device();
static void Main(string[] args)
{
device.HandleDataUpdate("50");
}
}
public class Device
{
public class Potentiometer : Level
{
public override void Action()
{
Console.WriteLine("value is at: {0}", this.Value);
}
}
public void HandleDataUpdate(String data)
{
Potentiometer.Value = Convert.ToDouble(data);
}
}
public class Level
{
private Double thisValue;
public Double Value
{
get => thisValue;
set
{
if (thisValue != value)
{
thisValue = value;
Action();
}
}
}
public virtual void Action()
{
}
}
}
Give Level
a protected abstract method OnSetValue
, forcing each subclass to override it. Now the setter of Value
can call OnSetValue
before the value is set:
public class Level {
private double val;
public double Value {
get {
return val;
}
set {
OnSetValue(value);
val = value;
}
}
protected abstract void OnSetValue(double val);
...
}
public class Potentiometer : Level {
protected void OnSetValue(double val) {
...
}
}
You need to create an instance of Potentiometer.
You're trying to set value of class field, which is impossible, not of object's field. You have to make instance of Potentiometer
inside the Device
, if you want to do this , you could make method or change code logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.