Access to the static property of a universal class?

I use Height for all members of Foo . Like this

 public class Foo<T> { public static int FoosHeight; } public partial class Form1 : Form { public Form1() { InitializeComponent(); Foo<???>.FoosHeight = 50; // DO I Set "object" here? } } 

The same situation is observed in VB.NET.

+7
generics
source share
3 answers

You will need to add some general type to it. At the same time, I sometimes use some kind of inheritance scheme to get this functionality without adding a generic type parameter.

 public class Foo { public static int FoosHeight; } public class Foo<T> : Foo { // whatever } public partial class Form1 : Form { public Form1() { InitializeComponent(); Foo.FoosHeight = 50; // DO I Set "object" here? } } 

At the same time, this will support the same FoosHeight, regardless of the generic type parameter passed to Foo<T> . If you want a different value for each version of Foo<T> , you will need to select the type to enter this type parameter and forget the inheritance scheme.

+13
source share

You need to specify the type, e.g.

 Foo<int>.FoosHeight = 50; 

or

 Foo<Bar>.FoosHeight = 50; 

but each is separate. Foo<int>.FoosHeight does not apply to Foo<Bar>.FoosHeight . They actually represent two separate classes with two different static fields. If you want the value to be the same for all Foo <>, then you need a separate place to store it, for example

 FooHelper.FoosHeight = 50; 

And FooHelper has no formal relationship with Foo <>.

+7
source share

Each particular family tree is its own type and therefore has its own static variable. Thus, Foo<int> will have a different element of static height than Foo<string> . If you want this to be common among all Foo<T> types, you need to implement this somewhere else.

If you really want to set the value for the type Foo<object> , but simply: Foo<object> .

+2
source share

All Articles