简体   繁体   English

C#将动态转换为字符串的最佳方法

[英]C# Best way to convert dynamic to string

The following gets a field from a DataTable and converts it to string.下面从 DataTable 中获取一个字段并将其转换为字符串。 Is there a cleaner way to convert dynamic to string?有没有更简洁的方法将动态转换为字符串?

dynamic value = dataTable.Rows[i].Field<dynamic>(columnName);
value = (value == null) ? null : value.ToString();
string value = Convert.ToString(dataTable.Rows[i][columnName]);

标准格式将启动,无需泛型、扩展方法或动态等内容。

First of all as Marc mentioned in his answer " the standard formatting will kick in, without the need for things like generics, extension methods or dynamic " , so in your case you don't have to use dynamic keyword , you can just convert directly to string, but talking about converting from dynamic to string I have two ways:首先,正如Marc在他的回答中提到的“标准格式将生效,不需要泛型、扩展方法或动态之类的东西”,所以在你的情况下,你不必使用dynamic关键字,你可以直接转换到字符串,但谈到从动态转换为字符串我有两种方法:

First way第一种方式

string x = Convert.ToString(value) // value is a dynamic object

pros: this is a good way of conversion if you are not sure whether the compiled data type supports casting to string or it's hard coded as int for instance,优点:如果您不确定编译后的数据类型是否支持转换为字符串或硬编码为int ,这是一种很好的转换方式,

cons: this way can cause errors if your are trying to make Convert.ToString(value) // value is a dynamic object inside an Extension Method , when I do so it gives me this error : "Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax" .缺点:如果您尝试使Convert.ToString(value) // value is a dynamic object Extension Method中的动态对象,这种方式可能会导致错误,当我这样做时,它会给我这个错误: “Extension methods cannot be dynamic dispatched. Consider强制转换动态参数或调用没有扩展方法语法的扩展方法”

so if you are for example using Asp.Net Core HttpContext.Session.SetString() and you put Convert.ToString(value) // value is dynamic object as an inline conversion in the arguements it will give you the error in the cons secion, to resolve this you can assign a variable outside the function arguments to the Covert.ToString(value) result then send the variable to the extension function arguements :因此,例如,如果您使用 Asp.Net Core HttpContext.Session.SetString()并且您将Convert.ToString(value) // value is dynamic object作为争论中的内联转换,它将在 con secion中为您提供错误,要解决此问题,您可以将函数参数之外的变量分配给Covert.ToString(value)结果,然后将变量发送到扩展函数争论:

dynamic value = 10;
HttpContext.Session.SetString("key",Convert.ToString(value));  <-- error

resolve:解决:

dynamic value = 10;
string x = Convert.ToString(value);
HttpContext.Session.SetString("key",x);  // works fine

or use the second way (casting), make sure the compiled data type supports casting to string或者使用第二种方式(强制转换),确保编译后的数据类型支持强制转换为字符串

HttpContext.Session.SetString("key",(string)value);

Second Way第二种方式
cast dynamic to string if the compiled data type supports it如果编译的数据类型支持,则将dynamic 转换string

string x = (string)value;  //value is dynamic object

pros: -it's useful if you want to make inline conversion inside an Extension method arguements -also useful if you want to make sure that the compiled data type supports casting to string and generate an exception based on this优点: - 如果您想在扩展方法争论中进行内联转换,这很有用 - 如果您想确保编译的数据类型支持转换为字符串并基于此生成异常,这也很有用

cons: this doesn't work on all data types so if you want a more generic conversion method the first way is recommended缺点:这不适用于所有数据类型,因此如果您想要更通用的转换方法,建议使用第一种方法


as mentioned here in MS docs "The dynamic type enables the operations in which it occurs to bypass compile-time type checking . Instead, these operations are resolved at run time. "正如MS 文档中提到的“动态类型使发生的操作能够绕过编译时类型检查。相反,这些操作是在运行时解决的。

So the dynamic variable's data type is compiled at run time and takes a type other than dynamic , and you can use casting if the interpreted object supports it or use Convert.ToString() for more generic type conversion.所以dynamic变量的数据类型是在运行时编译的,并且采用dynamic以外的类型,如果解释的对象支持它,您可以使用强制转换,或者使用Convert.ToString()进行更通用的类型转换。

PS: if you are converting to a data type other than string you may face data loss , like converting float to int , so be aware of that. PS:如果您要转换为字符串以外的数据类型,您可能会面临数据丢失,例如将 float 转换为 int ,因此请注意这一点。

I have a case where the dynamic should be a string, but in an error case is a number (code I call into and can't change is doing that).我有一种情况,动态应该是一个字符串,但在错误情况下是一个数字(我调用并且无法更改的代码就是这样做的)。

In my case I do:就我而言,我这样做:

string x = value as string;
if (x == null)
{
   // error condition
} else {
   //use x here
}

Convert.ToString doesn't work for me since my data are double[][] and result will be "System.Double[][]" Convert.ToString 对我不起作用,因为我的数据是 double[][] 并且结果将是“System.Double[][]”

double[,] figure_geometry = new double[2, 2] { { 1.0, 1.0 }, { 2.0, 2.0 } };
string geometry = JsonSerializer.Serialize(figure_geometry);

Works well效果很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM