有4类A, B, A1, and B1
。
A1
是A
和
B1
是B
的子类;
类A
有一个属性B
;
如何正确访问B1
类中的A1
属性?
下面的问题是演示,也是两个可能的解决方案。
解决方案N1存在一个问题,即同一个对象存储在两个属性中。
解决方案N2有一个问题,您必须在每次需要该属性时都对其进行转换;
有什么更好的方法吗?
最小代码示例:
public class A
{
public A(B foo)
{
this.foo = foo;
}
public B foo { get; set; }
}
public class B {}
public class A1 : A
{
// way N1 to do it.
public B1 b1_foo { get; set; }
public A1(B1 foo) : base(foo)
{
// way N1 to work
this.b1_foo = foo;
}
public void SomeMethod()
{
// access way by N1
var val = b1_foo.SomeProperty;
// N2 way to access B1's SomePropery
val = ((B1)this.foo).SomeProperty;
}
}
public class B1 : B
{
public int SomeProperty {get;set;}
}
发布于 2022-07-22 13:34:16
这就是我们可能使用泛型的地方。这可能会帮助你(我希望),或者它可能打开一个全新的世界的混乱。
看起来,A1
存在的唯一原因是它可以使用B1
而不是B
。
为了使它具有可读性,我使类名稍微长了一点,所以我从以下几个方面开始:
public class ThingA
{
public ThingA(ThingB foo)
{
this.Foo = foo;
}
public ThingB Foo { get; set; }
}
public class ThingB { }
public class ThingBWithExtraProperty : ThingB
{
public int SomeProperty { get; set; }
}
您可以创建这样一个类:
public class GenericThingA<T> where T : ThingB
{
public GenericThingA(T foo)
{
this.Foo = foo;
}
public T Foo { get; set; }
}
泛型参数-- <T>
--意味着当创建类的实例时,必须指定T
是什么。约束where T : ThingB
意味着无论T
是什么,它要么是ThingB
,要么继承它。
因此,假设您有一个ThingBWithExtraProperty
实例。你能做到的。
var thingB = new ThingBWithExtraProperty();
var genericThingA = new GenericThingA<ThingBWithExtraProperty>(thingB);
现在,对于这个类实例,Foo
的类型是ThingBWithExtraProperty
。因此,如果您想访问该属性,可以调用
var propertyValue = genericThingA.Foo.SomeProperty;
你几乎可以肯定已经对此熟悉了。这就像创建一个List<DateTime>
一样。泛型类型是List<T>
。T
可以是任何东西,但是当我们创建一个List<DateTime>
时,这意味着列表中的所有对象都是DateTime
。
这是更多关于泛型的文档。
这是一个我自己的博客。第二个原因是,一旦我们了解了泛型,有时我们会尝试用它们解决一些没有意义的问题,结果变得非常复杂。我学到了艰难的方法。
https://stackoverflow.com/questions/73084694
复制