将对象变量中保存的字符串分配给动态 (C#) 的字符串属性
我知道这有点拗口,可能无法完全理解。这是我正在尝试做的一个例子。
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;
这段代码令人惊讶地生成了一个错误RuntimeBinderException:无法隐式地将类型“object”转换为“string”
。 尽管 MyString
是 string
类型,并且 o
中保存的是 string
。
这是 DLR 的错误还是缺陷?
有办法绕过它吗?
如果我提前不知道类型。但我确实知道它符合鸭子类型。即我知道它实现了一个不成文的接口。当一个变量确实是正确的类型时,我是否可以将一个变量分配给另一个变量?
太感谢了
I know its a bit of a mouthful and may not be totally understandable. So here is an example of what I am 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 surprisingly generates an error RuntimeBinderException: Cannot implicitly convert type 'object' to 'string'
.
Even though MyString
is of type string
and what is being held in o
is a string
.
is this a bug or a shortcoming in the DLR?
Is there a way to get around it?
If I do not know the type ahead of time. But I do know that it complies with duck typing. i.e. I know that it implements an unwritten interface. Is there anyway I can assign one variable to the other when they really are the correct type?
Thank you so much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,这是预期的。编译器知道
o
的类型是object
,因此它记录了一个动态动作“尝试找到一个名为MyString
的属性,然后尝试为其分配一个object
类型的值” - 如果存在object
到string
的隐式转换,它可以做到这一点,但没有' t。请注意,语句中唯一动态的部分是它的目标...因此这是唯一动态处理的部分。在执行时,“执行时编译器”实际上会说,“d
值的实际类型是什么?啊,它是 TypeWithString...现在,如果我们有: 会发生什么?” ..并且会发生编译时错误,
如果您希望它在值中也动态表现,只需使用
dynamic
而不是object
作为值。你分配:这一次,“执行时编译器”将询问自己
d
和o
值的实际类型,并想象像这样的代码:No, this is expected. The compiler knows the type of
o
isobject
, so it records a dynamic action of "try to find a property calledMyString
and then try to assign a value of typeobject
to it" - it could do that if there were an implicit conversion ofobject
tostring
, but there isn't. Note that the only part of your statement which is dynamic is the target of it... so that's the only bit which is treated dynamically. At execution time, the "execution-time compiler" will effectively say, "What's the actual type of the value ofd
? Ah, it's TypeWithString... now, what would happen if we had:... and what would happen would be a compile-time error.
If you want it to behave dynamically in the value as well, just use
dynamic
instead ofobject
for the value you assign:This time, the "execution-time compiler" will ask itself for the actual type of both
d
ando
values, and imagine code like this:您始终可以尝试
d.MyString = o as string;
,它将把 o 强制转换(不抛出)到字符串,如果强制转换不存在,则将其强制转换为 null。You could always try
d.MyString = o as string;
which will cast (without throwing) o to a string or null if cast doesnt exist.