I use a Height
for all the Foo
s members. 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 in VB.NET.
Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.
A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static class. You can have a static constructor in a static class but you cannot have an instance constructor inside a static class.
In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
You'd have to put some generic type parameter in there. That being said, I'll sometimes use some kind of inheritance scheme to get this functionality without having to put in the 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?
}
}
That being said, this will keep the same FoosHeight regardless of the generic type parameter passed into Foo<T>
. If you want a different value for each version of Foo<T>
, you'll have to pick a type to put in that type parameter, and forget the inheritance scheme.
You need to specify a type, such as
Foo<int>.FoosHeight = 50;
or
Foo<Bar>.FoosHeight = 50;
but each is separate. Foo<int>.FoosHeight
is not related to Foo<Bar>.FoosHeight
. They're effectively two separate classes with two distinct static fields. If you want the value to be the same for all Foo<> then you need a separate place to store it like
FooHelper.FoosHeight = 50;
And FooHelper has no formal relationship with Foo<>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With