我想检查的对象是一个数字,这样.ToString()
会导致包含数字和字符串+
,-
,.
是否可以通过简单的类型检查.net(如:)if (p is Number)
?
或者我应该转换为字符串,然后尝试解析加倍?
更新:澄清我的对象是int,uint,float,double等等它不是一个字符串.我正在尝试创建一个将任何对象序列化为xml的函数,如下所示:
<string>content</string>
Run Code Online (Sandbox Code Playgroud)
要么
<numeric>123.3</numeric>
Run Code Online (Sandbox Code Playgroud)
或提出例外.
但这是一个例子:
Dim desiredType as Type
if IsNumeric(desiredType) then ...
Run Code Online (Sandbox Code Playgroud)
编辑:我只知道类型,而不是字符串的值.
好的,不幸的是我必须循环使用TypeCode.
但这是一个很好的方法:
if ((desiredType.IsArray))
return 0;
switch (Type.GetTypeCode(desiredType))
{
case 3:
case 6:
case 7:
case 9:
case 11:
case 13:
case 14:
case 15:
return 1;
}
;return 0;
Run Code Online (Sandbox Code Playgroud) 使用 .Net Core 3 的新 System.Text.Json JsonSerializer,如何自动转换类型(例如 int 到 string 和 string 到 int)?例如,这会引发异常,因为id
在 JSON 中是数字,而在 C# 中需要Product.Id
一个字符串:
public class HomeController : Controller
{
public IActionResult Index()
{
var json = @"{""id"":1,""name"":""Foo""}";
var o = JsonSerializer.Deserialize<Product>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
});
return View();
}
}
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Newtonsoft 的 Json.Net 很好地处理了这个问题。如果您在 C# 期望字符串时传入数值并不重要(反之亦然),一切都按预期反序列化。如果您无法控制作为 JSON 传入的类型格式,您如何使用 System.Text.Json 处理此问题?
有没有办法将类型数组传递给“is”运算符?
我正在尝试简化针对多种类型检查对象的语法。
就像是:
public static function bool IsOfType(object Obj,params Type[] Types)
Run Code Online (Sandbox Code Playgroud)
但是,这需要以下用法:
if(X.IsOfType(typeof(int),typeof(float))
{...}
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情:
if(X is {int,float})
Run Code Online (Sandbox Code Playgroud)
或者
if(X.IsOfType(int,float))
Run Code Online (Sandbox Code Playgroud)
甚至
public static bool ISOfType<T[]>(this object Obj){...}
if(X.ISOfType<int,float>())
Run Code Online (Sandbox Code Playgroud)
我认为他们都是不可能的。
从控制台应用程序运行时,此语句将“x”设置为true
:
var x = 3.GetType().IsAssignableTo(typeof(INumber<>)); // x == true
Run Code Online (Sandbox Code Playgroud)
在单元测试中运行时相同的语句设置x
为false
。为什么?
c# ×4
.net ×3
.net-7.0 ×1
.net-core ×1
arrays ×1
asp.net-core ×1
generics ×1
json.net ×1
mstest ×1
reflection ×1