Question

The function below returns a type of Dynamic, what is the most efficient way to cast it to IDictionary

 public dynamic GetEntities(string entityName, string entityField)
Était-ce utile?

La solution

I'd probably go with the as operator.

var result = GetEntities("blah", "blahblah") as IDictionary<string,string>;

Then do a null check.

UPDATE

In regards to the "efficient" part of your question, I think as may be pretty efficient compared to some other paths you could take:

  1. You could just blindly cast it to IDictionary<string,string> and then catch the exception, but using exceptions for control flow isn't a good idea and is expensive.
  2. You could use a convention like expression is type ? (type)expression : (type)null, but in this case, you evaluate expression twice (but you do get a null if the expected type isn't the type that expression returns). So you're doing double evaluations.
  3. as is only good for reference or boxing conversions, not to perform user-defined conversions, so if you need that, then as isn't for you.

See this article on MSDN.

UPDATE 2

I made an assumption on the key/value types of the IDictionary. You could just use IDictionary after as instead of specifying the generic type parameters. I guess it depends on what you're expecting.

Hope this helps.

Autres conseils

var dict = GetEntities(entityName, entityField) as IDictionary

or

var dict = GetEntities(entityName, entityField) as IDictionary<string,string>

This way:

IDictionary dictionary = GetEntities("", "") as IDictionary;

Then either dictionary will be your object, or it will be null - depending on result type of GetEntities.

IDictionary dict = GetEntities(name, field) as IDictionary;

Then check for null and everything's fine. If you don't want that dict is null, but it throws an exception instead, use

IDictionary dict = (IDictionary) GetEntities(name, field);

try this:-

 var dict = GetEntities(entityName, entityField) as IDictionary<string,string>

It really depends what is the underling type of dynamic

If it is converted to dynamic from IDictionary, you can simply cast it

var dict = GetEntities(entityName, entityField) as IDictionary

if not, things become complicated, and it is not always possible to do

In this case you first need to check underling type by calling GetType method, if it is managed type and not DynamicObject, you are lucky, use reflection, if it is DynamicObject, I don't think there is any way to convert it to dictionary, because it may have custom implementation and even reflection doesn't work in this case

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top