如何在包含一个变量的类中使用多个属性? [英] How to use multi properties in class that contain one variable?
问题描述
你好.
如果您能帮助我,将不胜感激.我有一个名为config的类,该类具有名为param的私有字符串变量.
我需要从config类的param变量中获取,有时以int类型获取,有时以bool类型或字符串获取.
据我了解,我需要在config类中创建3个属性,每个属性都必须转换类型,如下所示:
第一个属性将字符串转换为int,第二个属性将字符串转换为bool,第三个属性为我获取字符串值.
该类应该看起来像这样.
Hello.
Would be very grateful if you help me. I have class named config that have private string variable named param.
I need to get from config class param variable sometimes as int type sometimes as bool type or string.
As I understand I need create 3 properties in config class,each property have to convert type, as follow:
the first property converts string to int, the second converts string to bool, the third property gets me the string value.
The class should look something like this.
class Config
{
private string param;
public int
{
get
{
return int.parse(param);
}
}
public bool
{
get
{
return bool.tryparse(param);
}
}
public string
{
get
{
return param;
}
}
}
但是我不知道如何根据我要离开课堂的变量类型使用这些属性.
我希望你能帮帮我!!
But I dont know how can those properties be used in accordance to the variable type that I want to get out of class.
I hope you can help me!! Thank you in advance!
推荐答案
即使请求有点奇怪,也应该是解决方案(即使从概念上讲是错误的):
Even if the request is a kind of strange, this should be the solution (even if it is conceptually wrong):
public class Config
{
private string param;
public bool MyBool
{
get { return bool.Parse(param); }
}
public int MyInt
{
get { return int.Parse(param); }
}
public string My
{
get { return param; }
}
}
然后将其简单地用作:
Then use it simply as:
Config c = new Config();
int i = c.MyInt;
干杯
Cheers
这篇关于如何在包含一个变量的类中使用多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!