如何在Class类型引用变量中存储字符串类型值? [英] How to store a string type value in Class type reference variable?

查看:98
本文介绍了如何在Class类型引用变量中存储字符串类型值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类引用:

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 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; }
   }


这篇关于如何在Class类型引用变量中存储字符串类型值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆