簡體   English   中英

c# 有沒有辦法確定一個對象的值是像整數和字符串這樣的基類型,還是像類或結構這樣的基類型

[英]c# Is there a way to determine if an object value is a base type like ints and strings or like class or structs

我想制作一個序列化程序,為此我必須檢查當前對象的類型是否可以保存多個值。 (我所說的基本類型是字符串和整數)

我知道互聯網上有很多很棒的序列化器,但我這樣做是一種挑戰,而且它們中的大多數都沒有我想要的功能

我猜整數和字符串也是類,但我想要的是這樣的:

bool CheckIfBaseType(object value)  { return //check }

我認為沒有正確的方法可以做到這一點,而不是將每個基本類型保存在一個數組中

編輯:

我想我可以使用反射來檢查是否有任何公共變量,但有沒有更好的方法來做到這一點?

編輯2:

好的,我將嘗試再解釋一下,所以我真正想要的是一個可以檢測一個值是否可以保存另一個值的函數,以便我可以檢查子值

算法解釋:

    if(objectCanHoldValues(value))
    {
        //switch the target object to the child object and check if 
        it can hold a value (this part is done)
    }

當我說您的解決方案不起作用時,請不要不喜歡。 如果我犯了錯誤,我對堆棧溢出真的很陌生,對不起

這就是你要找的東西?

public static class TypeExtensions
{

    private static HashSet<Type> otherScalarTypes = new HashSet<Type>
    {
        typeof(string), typeof(Guid), typeof(DateTime),
        typeof(DateTimeOffset)
    };

    public static bool IsScalar(this Type type)
    {
        return type.IsPrimitive || otherScalarTypes.Contains(type);
    }
}

請注意,Boolean、Byte、SByte、Int16、UInt16、Int32、UInt32、Int64、UInt64、IntPtr、UIntPtr、Char、Double 和 Single 是原始類型。

然后您可以檢查它是否是“基本類型”:

if (obj.GetType().IsScalar()) 
{

}

使用 .Net Reflection 檢查 IsPrimitive、IsArray 或其他類型

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM