c# - 在 C# 中动态设置属性类型

标签 c# parsing reflection types properties

我的数据流出现以下问题:

数据流由一个字典组成,我想动态解析并指定值的类型。

即我的数据流包括:

  • “日期”,“2000 年 1 月 1 日”
  • "名字", "乔"
  • “活着”,“真实”
  • “健康”,“100”

现在我想根据这个数据流设置泛型类的属性:

class GenericClass
{
    Hashtable genericAttributes;
}

是否可以通过反射将我的数据流值设置为正确的类型?

我可以尝试这样的事情:

DateTime.TryParse(date, out myDate);

对于日期时间对象,但我认为这在尝试解析 double 、 float 、int16s、int32s、uint16 时不会起作用,...

有什么想法吗?

致谢和问候

最佳答案

根据您的问题,我的猜测是它们都是 IConvertible,因此我将在下面的代码示例中执行一些操作。我的想法是我指定“想要”的顺序,即如果类型可以适合多种类型,则按我想要的顺序排列,然后我尝试按该顺序转换它们。

    public class GenericPropClass
    {
        public Type type;
        public object value;
        public string key;
    }

    [TestMethod]
    public void PropertySet()
    {
        var dict = new Dictionary<string, string>();
        var resultingList = new List<GenericPropClass>();
        // Specify the order with most "specific"/"wanted" type first and string last
        var order = new Type[] { typeof(DateTime), typeof(int), typeof(double), typeof(string) }; 

        foreach (var key in dict.Keys)
            foreach (var t in order)
            {
                try
                {
                    var res = new GenericPropClass()
                    {
                        value = Convert.ChangeType(dict[key], t),
                        key = key,
                        type = t,
                    };
                    resultingList.Add(res);
                    break;
                }
                catch (Exception)
                {
                    // Just continue
                }
            }

    }

很抱歉,这个简短的回答几乎只包含代码,今晚我可能有时间改进它以了解我的想法,但我现在必须走了:)

关于c# - 在 C# 中动态设置属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13194172/

相关文章:

Python - 从域名和页面标题解析公司名称

java - HTML类型字符串解析问题!

c# - 反射将 css 类添加到 body 标记 c#

c# - 如何在 Windows 移动应用程序中存储字符串值并在以后检索它

c# - 在c#windows phone 7中计算PM和AM之间的时间差

c# - 自动修剪位图到最小尺寸?

c# - 我如何反射(reflect)动态对象的成员?

c# - 如何在 ASP.NET 中显示来自 C# 的警告框?

java - 解析java xml文件中的字符串

c# - 在运行时确定是否允许转换 (C#)