简体   繁体   中英

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)?

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:

SomeType a = AClassWithALongNameIDontWantTotType

and then be able to do

a.methodA()

?

I can get out a function by doing something like

Func<bool> a = AClassWithALongNameIDontWantTotType.methodA() 

but I would prefer to have the whole 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. You can accomplish what you're looking for through Reflection or dynamic. To do this I created a DynamicObject to help:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM