如何在Class类型引用变量中存储字符串类型值? [英] How to store a string type value in Class type reference variable?
问题描述
我有一个类引用:
DeviceType deviceType
和字符串类型变量
string device_Type
如何将deviceType中的值存储到此类型参考deviceType?
这里是代码:
I have a class reference:
DeviceType deviceType
and a string type variable
string device_Type
How do i store the value from deviceType to this class type reference deviceType?
here is the code:
public enum DeviceType
{
Unknown,
Mesa = 1,
Pulnix,
Vitrionics,
DriveSafe
}
和
i有:
string deviceType;
现在我需要存储在这个DeviceType变量中的任何值。
i意味着
DeviceType dev_Type;
dev_Type =< here i =need =to =get =devicetype =which which =is =string =type =data => ??
and
i have :
string deviceType;
now whatever value i am getting I need to store in this DeviceType variable.
i mean
DeviceType dev_Type;
dev_Type=<here i="" need="" to="" get="" devicetype="" which="" is="" string="" type="" data=""> ??
推荐答案
你好再次安舒马,
现在我明白了你的问题。问题是如何在枚举值和它的字符串表示(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 aParse
function implemented on theEnum
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 aclass
, it is anenum
, so the variabledeviceType
is aenum
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; }
}
这篇关于如何在Class类型引用变量中存储字符串类型值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!