本文介绍了使课程返回字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以让类默认情况下返回其字段之一:

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"

如何实现此目的?

推荐答案

对于所有那些说不可能的人,)

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

用法:

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

礼物:

alpha

注意 Console.WriteLine test 作为 string 并调用 Console。由于隐式转换,WriteLine(字符串值)重载。

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

这篇关于使课程返回字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:22