Assign a string contained in an object variable to a dynamic row property (C #)

I know that he has a little throat and, perhaps, is not entirely clear. So here is an example of what I'm trying to do.

public class TypeWithString
{
    public string MyString { get; set; }
}

string s = "We Want Moshiach Now";
TypeWithString tws = new TypeWithString();
object o = s;
dynamic d = tws;
d.MyString = o;

This code unexpectedly generates an error RuntimeBinderException: Cannot implicitly convert type 'object' to 'string'. Even if it MyStringhas a type string, but what is in ois string.

Is this a bug or a flaw in DLR?

Is there any way around this?

If I do not know the type ahead of time. But I know that it matches the sign of ducks. those. I know that it implements an unwritten interface. In any case, can I assign one variable to another when they are really the correct types?

Thank you very much

+3
2

, . o is object, " MyString, object" - object string, . , , , ... , . " " : " d? , TypeWithString... , , :

TypeWithString tmpD = (TypeWithString) d;
tmpD.MyObject = o;

... , .

, , dynamic object :

string s = "We Want Moshiach Now";
TypeWithString tws = new TypeWithString();
dynamic o = s;
dynamic d = tws;
d.MyString = o;

" " d o :

TypeWithString tmpD = (TypeWithString) d;
string tmpO = (string) o; // Actual type is string at execution time
tmpD.MyObject = tmpO;
+4

d.MyString = o as string;, ( ) o null, .

+1

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


All Articles