如何返回类的属性而不是类本身? [英] How to return a property of the class instead of the class itself?
问题描述
我目前正在使用隐式运算符将类转换和转换为 Class2
。
I'm currently converting and casting from Class to Class2
using the implicit operator.
想要做的是,每当我提到 foo(Class< Class2>)
,我想要 Goo(Class)
以便我可以直接访问它的公共属性,而不必将它首先投射到一个新的变量。
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.
换句话说,当我访问 Class< Class>
时,我想要返回Goo。
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();
}
}
编辑#1:更新代码。 >
EDIT #1: Updated the code.
推荐答案
你应该能够很简单地在类中实例化它。
you should be able to do it quite simply as you have already instantiated it within the class.
Class2 main = foo.Goo
这篇关于如何返回类的属性而不是类本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!