如何在mvc 4中从控制器访问私有构造函数到模型类

时间:2016-08-20 09:07:26

标签: c# asp.net-mvc-4 deserialization

有没有办法从控制器访问私有构造函数到模型?
包含调用模型的方法的控制器如下:

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; }
}

1 个答案:

答案 0 :(得分:2)

  

有没有办法从控制器访问私有构造函数到模型?

虽然这是解决问题的正确方式可能有争议,但问题本身可以通过 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

相关问题