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