最佳答案
我有一段将类型序列化为 Html 标记的代码块。
Type t = typeof(T); // I pass <T> in as a paramter, where myObj is of type T
tagBuilder.Attributes.Add("class", t.Name);
foreach (PropertyInfo prop in t.GetProperties())
{
object propValue = prop.GetValue(myObj, null);
string stringValue = propValue != null ? propValue.ToString() : String.Empty;
tagBuilder.Attributes.Add(prop.Name, stringValue);
}
这个工作非常好,除了我希望它只对基本类型执行此操作,如 int
、 double
、 bool
等,以及其他非基本但可以很容易序列化的类型,如 string
。我希望它忽略其他一切,如列表和其他自定义类型。
有人能告诉我该怎么做吗?还是需要指定要在某处允许的类型,然后打开属性的类型以查看是否允许?有点乱,所以如果我有更整洁的方式就好了。