我班上有以下枚举:
public enum InventoryType
{
EQUIP = 1,
USE = 2,
SETUP = 3,
ETC = 4,
CASH = 5,
EVAN = 6,
TOTEMS = 7,
ANDROID = 8,
BITS = 9,
MECHANIC = 10,
HAKU = 11,
EQUIPPED = -1
}
Run Code Online (Sandbox Code Playgroud)
现在,我有一个领域:
public InventoryType InventoryType { get; private set; }
Run Code Online (Sandbox Code Playgroud)
我从MySql加载数据.MySql的类型列具有InventoryType的字符串.如何将我得到的字符串转换为枚举InventoryType?
我试过了:
this.InventoryType = reader.GetString("type");
Run Code Online (Sandbox Code Playgroud)
但是,当然,这不起作用,因为它获得了一个字符串并需要一个InventoryType.我该怎么做才能转换它?谢谢.
说我有一个功能如何在记录上设置属性
public void SetProperty<TRecord, TEnum>(TRecord item,
Func<TRecord, TEnum> property, string enumValue )
where TEnum : struct
where TRecord : class
{
TEnum enumType;
if (Enum.TryParse(enumValue, true, out enumType))
{
//How Do I set this?
property.Invoke(item) = enumType;
}
}
Run Code Online (Sandbox Code Playgroud)
我不想把它换成表达式.有人知道如何设置属性吗?
这个问题可能已经回答了,但是老实说我不知道要寻找什么,“反射”并不能解决我的问题。
我想通过一个字符串来调用一个字段,例如:
string str = "Green";
Color colorForPurpose = Color.str;
Run Code Online (Sandbox Code Playgroud)
当然这是行不通的,但目的应该明确。
有人有主意吗?
在这个StackOverflow问题上,我发现了一个非常好的帮助程序方法,用于将字符串解析为通用Enum值:
public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
Run Code Online (Sandbox Code Playgroud)
我想将其从辅助方法更改为扩展方法,但我对使用泛型并不十分熟悉,因此不确定是否/如何使用泛型。
我尝试过此方法,但是您很快就会看到此代码实际上并未编译:
public static T ParseEnum(this T myEnum, string value)
{
return (T) Enum.Parse(typeof(myEnum), value, true);
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过这样做,但这也不起作用:
public static Enum ParseEnum(this Enum myEnum, string value)
{
return Enum.Parse(typeof(myEnum), value, true);
}
Run Code Online (Sandbox Code Playgroud)
甚至可以做我在这里问的事情吗?
我有一个像下面这样的枚举
public enum Colors
{
red,
blue,
green,
yellow
}
Run Code Online (Sandbox Code Playgroud)
我想用它开关盒
public void ColorInfo(string colorName)
{
switch (colorName)
{
// i need a checking like (colorname=="red")
case Colors.red:
Console.log("red color");
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Cannot implicitly convert type 'Color' to string
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助解决这个问题..
我是C#的新手,拥有其他语言的基础知识.我想出了这个问题:
public void startupMessage(string appTitle, string (((color))))
{ V--------V
Console.ForegroundColor = ConsoleColor.(((color)));
}
Run Code Online (Sandbox Code Playgroud)
我认为有些问题是第二个参数必须是字符串以外的东西.但我不确定.
我从输入中得到一个字符串,我想给它一个如下的索引:
例如:
string Name = "Jack"
Run Code Online (Sandbox Code Playgroud)
有5种可能性:
Jack = 1,
Alice = 2,
Stiven = 3,
Alex = 4,
Katrin = 5
Run Code Online (Sandbox Code Playgroud)
当我从输入中获取Name时,我想通过这个枚举类并获取它的索引