有什么方法可以从控制器访问模型的私有构造函数?
包含调用模型的方法的控制器如下:
public ActionResult ReadXML()
{
XmlSerializer reader = new XmlSerializer(typeof(List<Asseted>));
TextReader textReader = new StreamReader(@"D:\Tial2.xml");
List<Asseted> asseted;
List<Asseted> list = new List<Asseted>();
asseted = (List<Asseted>)reader.Deserialize(textReader);
textReader.Close();
for (int i = 0; i < asseted.Count; i++)
{
string data123 = Convert.ToString(asseted[i].PopertyValue);
string data234 = Convert.ToString(asseted[i].PropertyName);
list.Add(new Asseted(data123,data234));
}
return View();
}
包含要调用的方法的模型如下:
[XmlRoot]
public class Asseted
{
string pName, pValue;
private string data234;
private string data123;
private Asseted(string data234, string data123)
{
// TODO: Complete member initialization
PropertyName = data234;
PopertyValue = data123;
}
[XmlElement]
public string PropertyName { get; set; }
[XmlElement]
public string PopertyValue { get; set; }
}
有什么方法可以从控制器访问模型的私有构造函数?
虽然这是否是解决问题的正确方法可能会引起争议,但可以使用YES回答问题本身。而且反射起来也不是很难。
ConstructorInfo constructor = typeof(Asseted).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] { typeof(string), typeof(string) },
null);
Asseted instance = constructor.Invoke(new[] {
"data234",
"data123"
}) as Asseted;
基本上,您将获得类型(Asseted
),与您的已知参数类型匹配的构造函数并对其进行调用。完毕。
附加说明:根据您的编译器和实际代码,您可能会遇到TypeAccessException
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句