Why can't I refer to a type through an expression?

The following code seems impossible to compile no matter how hard I try to expose it: P can someone tell me what I'm doing wrong?

public class LUOverVoltage { public string Name { get; set; } public enum OVType { OVLH, OVLL } public List<string> PinGroups = new List<string>(); public void Add(string name, OVType type, string Grp) { this.Name = name; this.OVType = type; //Why cannot reference a type through an expression? PinGroups.Add(Grp); } } 
+4
source share
5 answers

You are misleading a field with an enumeration type with the enumeration type itself. Your code is about as useful as string="bla" .

 public enum OVType { OVLH, OVLL } public class LUOverVoltage { public string Name { get; set; } public OVType OVType { get; set; } 

Declares a type named OVType and a property with the same name. Your code should now work.


As a side note, both your type names and property names violate .net naming conventions.

I would name the enumeration type OverVoltKind and the property is just Kind .

+13
source

You are not setting a property, you are trying to set an enumeration.

Add public OVType ovType and use this.ovType = type .

 public class LUOverVoltage { public enum OVType { OVLH, OVLL } public string Name { get; set; } public OVType ovType; public List<string> PinGroups = new List<string>(); public void Add(string name, OVType type, string Grp) { this.Name = name; this.ovType = type; PinGroups.Add(Grp); } } 
+4
source

You defined Enum inside your class. What you have not done yet is to declare a variable to hold an instance of this enumeration.

 public enum OVType { OVLH, OVLL } public class LUOverVoltage { public string Name { get; set; } public OVType OVType { get; set; } public List<string> PinGroups = new List<string>(); public void Add(string name, OVType type, string Grp) { this.Name = name; this.OVType = type; // setting the property, not the enum definition PinGroups.Add(Grp); } } 
+2
source

OVType - not a field, its type

try it

 public class LUOverVoltage { public string Name { get; set; } public OVType Type {get; set;} public enum OVType { OVLH, OVLL } public List<string> PinGroups = new List<string>(); public void Add(string name, OVType type, string Grp) { this.Name = name; this.Type = type; PinGroups.Add(Grp); } } 
+1
source

OVType - type of variable. You set it to enum , which is the keyword used to declare a new enumeration type. You must declare OVType as an enumeration type, and then use it as a property type.

 public enum OVType { OVLH, OVLL } public class LUOverVoltage { public string Name { get; set; } public OVType OVType { get; set; } public List<string> PinGroups = new List<string>(); public void Add(string name, OVType type, string Grp) { this.Name = name; this.OVType = type; PinGroups.Add(Grp); } } 
0
source

Source: https://habr.com/ru/post/1380139/


All Articles