Make class return a field

牧云@^-^@ 提交于 2020-05-29 07:39:15

问题


Is there a way to make a class return one of its fields by default like that:

public class TestClass
{
    public string something;
}

TestClass test = new TestClass();
test = "alpha"; // "alpha" string is assigned to "something"
Console.Write(test); // test returns "alpha" string from "something"

How to make this work?


回答1:


For all those saying that's impossible,)

public class TestClass
{
    public string something;

    public static implicit operator TestClass(string s) => new TestClass { something = s};

    public static implicit operator string(TestClass testClass) => testClass.something;
}

Usage:

TestClass test = new TestClass();
test = "alpha";
Console.WriteLine(test);

Gives:

alpha

Note: Console.WriteLine takes test as string and calls Console.WriteLine(string value) overload thanks to implicit conversion.




回答2:


You can't make "a class return a field", but you can override its ToString method, so when it's printed with something like Console.Write you'll get the output you want:

public class TestClass
{
    public string Something {get; set;}

    public override string ToString()
    {
        return Somethig;
    }
}



回答3:


I would prefer to use the constructor and overload method ToString(), so you get an immutable object.

public class TestClass
{
    private readonly string something;

    public TestClass(string something)
    {
        this.something = something;
    }

    public override string ToString()
    {
        return something;
    }
}

TestClass test = new TestClass("alpha");
Console.Write(test);



回答4:


Is there a way to make a class return one of its fields by default?

No. Classes are not designed to return any value.

An alternative way to achieve what you mentioned in your question is defining property with get; set;, something like:

public class TestClass
{
    public string Something  { get; set; }
}

which you can use like:

TestClass test = new TestClass();
test.Something = "alpha"; // "alpha" string is assigned to "something"
Console.Write(test.Something); // test returns "alpha" string from "something"


来源:https://stackoverflow.com/questions/56823044/make-class-return-a-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!