Is there any limitations on the kind of characters that I can use to create a property for a dynamic object?

Is there a list of characters that I cannot use (e.g. / * @)?

有帮助吗?

解决方案

Suppose you have:

dynamic eo = new ExpandoObject();

then clearly if you expand the object through C# syntax, you need to follow the C# rules, for example:

eo.ValidCSharpIdentifier = 42;
eo._OK = 42;
eo.æ = 42;

But if you expand eo by casting to IDictionary<,>, then you can use other characters:

((IDictionary<string, object>)eo).Add("NotValidC#Identifier", 42);
((IDictionary<string, object>)eo).Add("42", 42);
((IDictionary<string, object>)eo).Add("/", 42);
((IDictionary<string, object>)eo).Add("*", 42);
((IDictionary<string, object>)eo).Add("@", 42);
((IDictionary<string, object>)eo).Add("", 42);

As we see, strange identifiers are possible. The string must be an object though, so a null reference cannot be used (as in .Add(null, 42) /* illegal */).

There seems to be no restriction on the name used. The string keys seem to be compared with an ordinal string comparison, like in EqualityComparer<string>.Default or StringComparer.Ordinal.

Certainly, some .NET languages have different rules for valid characters in names, compared to the C# rules.

其他提示

Any Unicode Standard Annex 15 character (and an underscore), as the C# spec says:

The rules for identifiers given in this section correspond exactly to those recommended by the Unicode Standard Annex 15, except that underscore is allowed as an initial character (as is traditional in the C programming language), Unicode escape sequences are permitted in identifiers, and the "@" character is allowed as a prefix to enable keywords to be used as identifiers.

For a list of characters that need prefix with @, take a look HERE.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top