c# - 是否可以在 C# 中为数组类型起别名?

标签 c# arrays types alias

我正在尝试使用自定义异常类型执行一些序列化/反序列化操作。此类型的字段定义为:

private object[] resourceMessageParams;

我已经得到了所有带有一些 Linq 表达式魔力的强类型代码,但我想更进一步,做这样的事情:

using ResourceMessageParamsType = object[];//<-- "Identifier expected" error here
/*...*/
private ResourceMessageParamsType resourceMessageParams;
/*...*/
this.resourceMessageParams = 
    (ResourceMessageParamsType)serializationInfo.GetValue(
        ReflectionHelper.GetPropertyNameFromExpression(() => 
            resourceMessageParams), typeof(ResourceMessageParamsType));

取而代之的是:

(object[])serializationInfo.GetValue(
    ReflectionHelper.GetPropertyNameFromExpression(() => 
        resourceMessageParams), typeof(object[]));

为了适应将来可能更改此字段的类型,因此只需在别名定义中更改一次类型。但是,编译器在 using ResourceMessageType = object[]; 中的 object 处停止,并提示需要标识符。更改为 Object[] 有所帮助,但这次括号突出显示了相同的错误消息。

有没有办法在 C# 中为数组类型定义别名?

最佳答案

您可以定义一个名为 ResourceMessageParamsType 的类(或结构),并定义隐式运算符以与 object[] 进行强制转换。

struct ResourceMessageParamsType
{
    private object[] value;

    private ResourceMessageParamsType(object[] value)
    {
        this.value = value;
    }

    public static implicit operator object[](ResourceMessageParamsType t)
    {
        return t.value;
    }

    public static implicit operator ResourceMessageParamsType(object[] value)
    {
        return new ResourceMessageParamsType(value);
    }
}

关于c# - 是否可以在 C# 中为数组类型起别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5655820/

相关文章:

c# - RAM获取帧的使用

c# - 分离表达式<Func<T, object>>

java - 使用用户定义的方法删除数组中的重复项

javascript - 我可以使用 constructor.name 来检测 JavaScript 中的类型吗

c++ - (class) 没有命名类型

C#:获取有关域中计算机的信息

c# - 使用 WCF 异步有好处吗?

c++ - 如何在 .h 和 .cpp 中为类中的私有(private)字符数组编写 get 函数?

arrays - 带有协议(protocol)的 Swift 泛型数组

c : 4x14bit + 1x8bit within a 64 bit 'container' 中的自定义数据类型