我在我的mvc应用程序中编写了以下代码。
public class TestController : Controller
{
public ActionResult StronglyTypedView()
{
var obj = new MvcRouting.Models.Student();
obj.age = 24;
obj.name = "prab";
ViewData.Model = obj;
return View();
}
}
在上面的代码中,ViewData
是ControllerBase
类的属性,而Model
是ViewDataDictionary
类的属性。我在下面的代码中试过但是我得到了property1中的null值,如何解决?
public interface Iface1
{
int age { get; set; }
}
public class classA : Iface1
{
public int age { get; set; }
}
public abstract class classB
{
public classA Property1 { get; set; }
}
public class TEST : classB
{
public void test()
{
Property1.age = 24;
}
public static void Main()
{
TEST obj = new TEST();
obj.test();
Console.Read();
}
}
答案 0 :(得分:3)
您将获得空引用异常,因为您需要在Property1
中初始化classB
public interface Iface1
{
int age { get; set; }
}
public class classA : Iface1
{
public int age { get; set; }
}
public abstract class classB
{
public classA Property1 { get; set; }
}
public class TEST : classB
{
public void test()
{
if(Property1 == null)
{
Property1 = new classA();
}
Property1.age = 24;
}
public static void Main()
{
TEST obj = new TEST();
obj.test();
Console.Read();
}
}
答案 1 :(得分:1)
改为使用它。
public abstract class classB
{
public classA Property1 { get; set; }
public classB()
{
Property1 = new classA();
}
}
答案 2 :(得分:0)
在设置其属性之前,您忘记初始化Property1
。
public class TEST : classB
{
public void test()
{
Property1 = new classA();
Property1.age = 24;
}
public static void Main()
{
TEST obj = new TEST();
obj.test();
Console.Read();
}
}