我有上课的属性。
例如
class Caption
{
public string AR{get;set;}
public string EN{get;set;}
pbulic string Tu{get;set;}
}
我想要例如直接将标题分配给副标题而无需调用属性
我要用这个
Caption caption=new Caption();
string myVar = caption; // this will return EN property directly
而不是
string myVar = caption.En;
我不知道,但我认为这里有重载字符串运算符或用于目标类本身的东西。
为什么我需要这个?仅出于本地化的目的,并且在本地化对象中具有更高的可读性。而每一次创建switch(language)
,然后分配caption.EN
,Caption.AR
。这将是丑陋的。
最干净的方法可能是实现索引器。这样一来,您就可以switch
一次在类中进行任何检查language
,处理问题,处理默认设置等操作,Caption
而无需调用方法,例如:
class Caption
{
public string AR { get; set; }
public string EN { get; set; }
public string Tu { get; set; }
// var cap = new Caption()[language];
public string this[string language]
{
get
{
var which = AR;
switch(language)
{
case nameof(EN):
which = EN;
break;
case nameof(Tu):
which = Tu;
break;
}
return which;
}
}
}
请注意,有可能实现您所需要的语法,在这里您可以将a隐式转换Caption
为string
。需要注意的是,language
在进行转换之前,您需要先了解。
您可以通过提供一个在创建时和/或使用一种方法(如果需要的话,可链接的)来处理它的构造函数来实现此目的,就像我在下面的操作中那样For
:
class Caption
{
public string AR { get; set; }
public string EN { get; set; }
public string Tu { get; set; }
// Gets the caption of the current language
public string Current { get; private set; }
// If the language is known in advance, you can return
// the desired language directly.
public static implicit operator string(Caption caption)
=> caption.Current;
public Caption For(string language)
{
var which = AR;
switch (language)
{
case nameof(EN):
which = EN;
break;
case nameof(Tu):
which = Tu;
break;
}
Current = which;
return this;
}
}
// Usage
var cap = new Caption
{
AR = "Test-ar",
EN = "Test-en",
Tu = "Test-tu"
}.For("EN");
string s = cap;
Console.WriteLine(s); // Test-en
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句