Practical uses of TypedReference

▼魔方 西西 提交于 2019-11-27 21:32:59

问题


Are there any practical uses of the TypedReference struct that you would actually use in real code?

EDIT: The .Net framework uses them in overloads of Console.WriteLine and String.Concat which build an array from an __arglist parameter and pass it to the normal params overload. Why do these overloads exist?


回答1:


Are there any practical uses of the TypedReference struct that you would actually use in real code?

Yes. I'd use them if I needed interoperability with C-style variadic methods.

Why do these overloads exist?

They exist for interoperability with callers who like to use C-style variadic methods.




回答2:


This appears to be a very old question, but I'd like to add one more use-case: when you have a struct and want to set its variable through reflection, you would always operate on the boxed value and never change the original. This is useless:

TestFields fields = new TestFields { MaxValue = 1234 };
FieldInfo info = typeof(TestFields).GetField("MaxValue");
info.SetValue(fields, 4096);

// result: fields.MaxValue is still 1234!!

This can be remedied with implied boxing, but then you loose type safety. Instead, you can fix this with a TypedParameter:

TestFields fields = new TestFields { MaxValue = 1234 };
FieldInfo info = fields.GetType().GetField("MaxValue");

TypedReference reference = __makeref(fields);
info.SetValueDirect(reference, 4096);

// result: fields.MaxValue is now indeed 4096!!


来源:https://stackoverflow.com/questions/1711393/practical-uses-of-typedreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!