[英]Can I assign a static class to a variable?
My question is whether I can assign a static class to another variable (and of what type would that be)?我的问题是我是否可以将 static class 分配给另一个变量(以及那将是什么类型)?
Say I have说我有
public static class AClassWithALongNameIDontWantTotType{
public static bool methodA() { stuff }
}
and then I have然后我有
class B{
}
Can I make it so that inside of class B
I can reassign this class to something with a shorter name, like:我可以这样做,以便在
class B
内部我可以将此 class 重新分配给名称较短的名称,例如:
SomeType a = AClassWithALongNameIDontWantTotType
and then be able to do然后能够做到
a.methodA()
? ?
I can get out a function by doing something like我可以通过执行类似的操作来获取 function
Func<bool> a = AClassWithALongNameIDontWantTotType.methodA()
but I would prefer to have the whole class.但我更愿意拥有整个 class。
Thanks!谢谢!
If you want this purely for the purpose of avoiding typing long names, you can use an alias如果您想要这样做纯粹是为了避免输入长名称,您可以使用别名
using a = SomeNamespace.AClassWithALongNameIDontWantToType;
No you can't, because you can't have an instance of a static class.不,你不能,因为你不能拥有 static class 的实例。 You can accomplish what you're looking for through Reflection or dynamic.
您可以通过反射或动态来完成您正在寻找的东西。 To do this I created a
DynamicObject
to help:为此,我创建了一个
DynamicObject
来帮助:
class StaticMethodProvider : DynamicObject
{
private Type ToWorkWith { get; set; }
public StaticMethodProvider(Type toWorkWith)
{
ToWorkWith = toWorkWith;
}
public override bool TryInvokeMember(InvokeMemberBinder binder,
object[] args, out object result)
{
result = ToWorkWith.InvokeMember(binder.Name, BindingFlags.InvokeMethod,
null, null, null);
return true;
}
}
and then you'd be able to do然后你就可以做
dynamic a = new StaticMethodProvider(
typeof(AClassWithALongNameIDontWantTotType));
Console.WriteLine(a.methodA());
But then you wouldn't have intellisense and compile time safety.但是那样你就不会有智能感知和编译时安全性。 It's probably a bit of overkill.
这可能有点矫枉过正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.