如何将 class 的 object 作为字符串运算符分配给变量?

How to assign an object of class as string operator to variable?

我有 class 有属性。

例如

class Caption
{  
   public string AR{get;set;}
   public string EN{get;set;}
   pbulic string Tu{get;set;}   
}

例如,我想直接将标题 object 分配给变量,而无需调用 属性

我想用这个

Caption caption=new Caption();
string myVar = caption;   // this will return EN property directly

而不是

string myVar = caption.En;

我不知道,但我认为有重载字符串运算符或针对 class 本身的东西。

为什么我需要这个?只是为了本地化的目的和本地化的更多可读性 object。 而是每次创建 switch(language) 然后分配 caption.ENCaption.AR。会很难看的

最干净的方法可能是实现索引器。这样你就可以 switch 一次,在 language 上做任何检查,处理问题,处理默认值等 Caption class 里面没有调用的仪式一个方法,像这样:

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

请注意,您可以在其中隐式地将 Caption 转换为 string 后实现语法。需要注意的是,在进行转换之前,您需要在某个时候知道 language

您可以通过提供一个构造函数来实现这一点,该构造函数在创建 and/or 时使用一种方法(如果您愿意,可以链接)来处理它,就像我在下面使用 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