我的数据流出现以下问题:
数据流由一个字典组成,我想动态解析并指定值的类型。
即我的数据流包括:
- “日期”,“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/