Dynamic Dictionary [C #]

Let's say I have a class called Compositethat contains a collection of another class Component, all of which have a property Name. It would be better to use Dictionarycomponent storage or it would be better to use a dynamic object.

For example, it would be better to do this:
Component component = someComposite.Components["RandomComponent"];
or this:
Component component = someComposite.Components.RandomComponent;

Where someComposite.Components dynamicin the second example.

The second case seems nicer, but there is no security like ...

I want to add that at some point I will end this:
DerivedComponent component = someComposite.Components["RandomComponent"] as DerivedComponent;
In this case, it dynamiccan save me when I enter the transformation.

So, the best design?

+3
source share
2 answers

, - : DerivedComponent = someComposite.Components [ "RandomComponent" ] DerivedComponent; , .

- ; - , . : ", , !"

, . , , , IDE, ... ( ).


, . dynamic , :

try
{
    DerivedComponent c = obj.RandomComponent;
    return c;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
    // do something here...
}
catch (InvalidCastException)
{
    // handle error
}

:

try
{
    var c = obj["RandomComponent"] as DerivedComponent;
    if (c == null)
        // deal with error...
    return c;
}
catch (KeyNotFoundException)
{
    // do something here...
}

, , .

+3

, , dynamic COM- , IronPython. dynamic all-#.

Dictionary < string, Component > .

System.ComponentModel (.. IContainer IComponent).

+6

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


All Articles