Is it possible to use alias array type in C #?

I am trying to perform some serialization / deserialization operations with a custom exception type. This type has a field defined as:

private object[] resourceMessageParams; 

I have nice and strongly typed code with some Linq expression magic, but I want to go even further and do something like this:

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

Instead of this:

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

To accommodate a possible change in the type of this field in the future, you need to change the type only once in the alias definition. However, the compiler stops at object in using ResourceMessageType = object[]; stating that an identifier is expected. Going to Object[] helps a little, but this time the bracket is highlighted with the same error message.

Is there a way to define an alias for an array type in C #?

+6
source share
4 answers

Simply put, you cannot use the types of the alias array.

You can get around this by encapsulating things in a struct , but this does not answer your question.


Update:

From ECMA standard

using the directive alias:

using identifier = namespace-type-name-name;

which explicitly says nothing about allowed arrays.

(see page 100 for how to name a namespace or namespace.)

+3
source

You can define a class (or structure) called ResourceMessageParamsType, and define implicit operators for casting to and from the [] 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); } } 
+7
source

I would just get my type from System.Array. If I correctly interpret what you are describing, this is a non-OO approach, as you would use in simple C.

Update. I guess you cannot subclass System.Array. There may be a way around.

0
source
 using ResourceMessageParamsType = System.Array; 

Not that I pretend to understand how this “protecting [s] serialization code from possible changes to the class definition” is for you.

Interfaces would be a cleaner approach, and were you considering generics?

The IMO Comprehensive Unit tests ensure that if someone changes the aliased type, all deserialization code will work.

0
source

Source: https://habr.com/ru/post/885863/


All Articles