How to return a property of the class instead of the class itself?

两盒软妹~` 提交于 2019-12-11 14:51:53

问题


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


来源:https://stackoverflow.com/questions/32179209/how-to-return-a-property-of-the-class-instead-of-the-class-itself

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