How to return a property of the class instead of t

2019-09-11 06:06发布

问题:

I'm currently converting and casting from Class to Class2 using the implicit operator.

But what I want to do is, that, whenever I refer to foo (Class<Class2>), I'd like for Goo(Class) to be returned so that I can access the public Properties of it directly, without having to cast it first into a new variable.

In other words, I want that when I access Class<Class>, I'd like Goo to be returned.

I'm aware I might have not been able to explain properly so feel free to ask in the comment section so that I can try to fill in even better on what I mean. Thanks in advance!

class Class<T> where T : new()
{
    public T Goo;

    public Class() { Goo = new T(); }

    public static implicit operator T(Class<T> Loo)
    {
        return Loo.Goo;
    }
}

class ClassX
{
    public byte[] SharedData;

    public ClassX() { }
}

class Class2 : ClassX
{
    public byte Data;

    public Class2() { }
}

class Class3 : ClassX
{
    public string Data;

    public Class3() { }
}

class Program
{
    static void Main(string[] args)
    {
        Class<Class2> foo = new Class<Class2>();
        Class2 poo = foo;

        foo.Data = 0xFF; // Error - I want this to work, tho.
        poo.Data = 0xFF; // Works - Not what I want to use.

        System.Console.ReadLine();
    }
}

EDIT #1: Updated the code.

回答1:

you should be able to do it quite simply as you have already instantiated it within the class.

Class2 main = foo.Goo