-1

假设我有类 A 和类 B 作为属性,每当分配 A 的实例时如何返回 AB 。例如:

public class A
{
    public B b {get; set;}
}

object x = A //Here I want to return A.b without casting it.

本质上重载了“=”运算符或为类本身提供了一个 get 语句。我可以在这里做什么?

4

1 回答 1

1

似乎是隐式运算符重载的工作,但我很少使用它,因为它很容易导致混淆:

public static class Program
{
    static void Main(string[] args)
    {
        var a = new A();
        B b = a;

        Console.WriteLine($"Name of b in a: {a.SomeB.Name}");
        Console.WriteLine($"Name of b: {b.Name}");
    }
}

public class A
{
    public A()
    {
        SomeB = new B { Name = Guid.NewGuid().ToString() };
    }

    public B SomeB { get; set; }

    public static implicit operator B(A a) => a.SomeB;
}

public class B
{
    public string Name { get; set; }
}

请注意,您的示例:

object x = A; // Here I want to return A.b without casting it.

永远不会工作,因为所需的类型必须在某处声明,object并不是真正的最佳候选者。

于 2021-09-27T15:20:39.300 回答