简体   繁体   English

如何定义命名空间范围的C#别名?

[英]How to define a namespace-wide C# alias?

It's possible to define an alias in C# like this 可以像这样在C#中定义别名

using kvp = System.Collections.Generic.KeyValuePair<string, string>;

var pair = new kvp("key", "value");

Microsoft define aliases too: Microsoft也定义了别名:

        int i;
        Int32 i2;

How can we define aliases that are available within a namespace? 我们如何定义命名空间中可用的别名? Is this configurable? 这是可配置的吗?


This question is specifically about an alias... so... using inheritance as a proxy isn't desired. 这个问题具体是关于别名......所以......不希望使用继承作为代理。 I'm happy with that in many situations... but not when you want the best of both descriptive names and a shorthand version. 在很多情况下我很满意......但是当你想要最好的描述性名称和速记版本时,我都不满意。

I don't think that what you're asking for is really possible. 我不认为你所要求的是真的可能。 Here's a workaround: include a type called kvp that is a copy of KeyValuePair<string, string> and implicitly converts to and from your type. 这是一个解决方法:包含一个名为kvp的类型,它是KeyValuePair<string, string>的副本,并隐式转换为您的类型。

public struct kvp
{
    public string Key { get; private set; }
    public string Value { get; private set; }

    public kvp(string key, string value)
        : this()
    {
        Key = key;
        Value = value;
    }
    public override string ToString()
    {
        return ((KeyValuePair<string, string>)this).ToString();
    }

    public static implicit operator KeyValuePair<string, string>(kvp k)
    {
        return new KeyValuePair<string, string>(k.Key, k.Value);
    }
    public static implicit operator kvp(KeyValuePair<string, string> k)
    {
        return new kvp(k.Key, k.Value);
    }
}

This has the effect of you being able to use kvp instead of KeyValuePair<string, string> , with no unintended effects in most cases. 这样可以使用kvp代替KeyValuePair<string, string> ,在大多数情况下不会产生意外影响。

If the type you wished to typedef were an unsealed class, you could do (something very close to) what you want by making a class that extends it, with all of the base class's constructors mirrored and extending base(...) . 如果你希望typedef的类型是一个未密封的类,你可以通过创建一个扩展它的类来做(非常接近)你想要的东西,所有基类的构造函数都被镜像并扩展base(...)

You are explicitly asking for an alias and not for a workaround. 您明确要求别名而不是解决方法。 Therefore, the only answer I have is: There is no way to do this. 因此,我唯一的答案是:没有办法做到这一点。

The using alias that you gave as an example is per file. 您提供的using别名是每个文件。 C# does not have a construct that allows cross-file aliases. C#没有允许跨文件别名的构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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