-
Hello, trying to find the solution to a problem I found that I cannot access a static property from a generic method. The code is like this: public class A
{
public static Guid identifier = new Guid("00000000-0000-0000-0000-000000000000");
}
public class B<T> where T : A
{
public int Method()
{
return T.identifier;
}
} Why is this not supported? I am missing something? Found a workaround using custom attributes and reflection, but I think that using reflection for that is suboptimal. |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments
-
Try A.identifier |
Beta Was this translation helpful? Give feedback.
-
Instead of |
Beta Was this translation helpful? Give feedback.
-
class A
{
public static int X => 0;
}
class C : A
{
public static new int X => 1;
}
class B<T> where T : A
{
public static int Y => T.X;
} I'm guessing this is the op's intent. |
Beta Was this translation helpful? Give feedback.
-
@khm1600 Yes, I'm looking for something like an |
Beta Was this translation helpful? Give feedback.
-
Also, take a look at the shapes proposal |
Beta Was this translation helpful? Give feedback.
-
@alexdrl Using a custom attribute and reflection seems like it is possibly your only choice here as "Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level." If performance is a concern, you could look at in memory caching using a dictionary on a static class to store the Type and PropertyInfo when using reflection to find the fields marked with the custom attribute. Just make sure the cache is thread-safe if you need it to be. |
Beta Was this translation helpful? Give feedback.
-
There is no such feature in .NET/CLR. That being said, such feature can be simulated easily with singleton classes as type class. Nothing fancy. That's also how they are implemented in languages supporting that. It is just that: it is a high level feature, while As an example: class ATypeClass {
public int X { get; set; }
}
class A {
public static ATypeClass TypeClassInstance = new ATypeClass();
public ATypeClass TypeClass { get { return TypeClassInstance; } }
} |
Beta Was this translation helpful? Give feedback.
-
I dont feel good about instance variable returning static value. |
Beta Was this translation helpful? Give feedback.
There is no such feature in .NET/CLR.
static
means no runtime dispatching. So no inheritance on static members.That being said, such feature can be simulated easily with singleton classes as type class. Nothing fancy. That's also how they are implemented in languages supporting that. It is just that: it is a high level feature, while
static
is already bound to the low level foundational feature, which many others rely on.As an example: