开发者

Can a class be aliased in C#?

In a namespace, is it possible to provide an alias for a class? And if not, why not?

By example, if I had several libraries of things that were derived from a contained, but named base class, but wanted to alias that as "BaseClass", while retaining its actual class name (i.e. "HtmlControl").

Then consumers cou开发者_JAVA百科ld always come along and extend from HtmlControls.BaseClass, without having to figure out which class it really comes from.


using SomeClass = Large.Namespace.Other.FunkyClass;

class Foo : SomeClass
{
}


There really isn't an ideal way to do this in C#/.NET. What you can do is have a public BaseClass that inherits from an internal class. You can change this inheritance internally without breaking your consumers as long as the interface to the class remains intact.

public class PublicBaseClass : SomeInternalClass {

}

Consumers inherit from PublicBaseClass, and as long as you are careful, you can change what SomeInternalClass is as you wish.


You could create a dummy class that just inherits HtmlControl without adding any other functionality:

public class BaseClass : HtmlControl {}


The closest I know of is to customize your using statement:

using BaseClass = HtmlControls.BaseClass;

This is normally used to avoid ambiguity between classes with the same name in different used namespaces, without having to fully qualify one or the other. Your devs would have to include it in every code file, so probably not a good solution for what you're doing.

As far as deriving from BaseClass without knowing what you are actually deriving from, not possible. The compiler must, at some level, know what and where the parent class is, meaning it must be statically defined somewhere in code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜