且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Class类型引用变量中存储字符串类型值?

更新时间:2023-11-06 21:31:10

你好再次安舒马,



现在我明白了你的问题。问题是如何在枚举值和它的字符串表示(Name)之间进行转换。你很幸运 - 在.net中这很简单 - 在 Enum 类上实现的 Parse 函数。像这样使用:



Hi again Anshumaan,

So now I understand your Problem. The question is how to covert between an enumeration value and it's string representation (Name). You are lucky - that's quite easy in .net - ther is a Parse function implemented on the Enum class. Use it like this:

string strDeviceType = "Pulnix";
DeviceType devicetype = (DeviceType) Enum.Parse(typeof(DeviceType), strDeviceType);





很酷,我想这就是你要求的,不是吗?



亲切的问候

Johannes



Cool, I think this is what you asked for, isn't it?

Kind regards
Johannes


在您的示例代码中,DeviceType不是,它是枚举,所以变量 deviceType 也是枚举(根本不是参考,它是一个ValueType)



你不能在枚举中添加,存储或以其他方式包含一个字符串:它是一个基于整数的变量类型,不能包含任何其他的。



你可以创建一个包含它们的类:

In your example code, DeviceType is not a class, it is an enum, so the variable deviceType is a enum as well (and isn't a reference at all, it's a ValueType)

You cannot add, store or otherwise include a string in an enum: it is a integer based variable type and cannot contain anythign else.

You could create a containing class which holds them both:
public class MyContainer
   {
   public DeviceType DeviceType { get; set; }
   public string Text { get; set; }
   }