简体   繁体   中英

How to call a class in Mvc action if a class within the another class

Here i write some class in another class but when i try to access the class why i'm not able to getting that class

namespace ImageWithallCtrls.Models
{
    public class GeneralAssClass
    {
         public class AccessClass2 :BaseAccessClass
         {
             private GeneralAssClass GenAss;
             public string L_Name { get; set; }

         }
         public class AccessClass1 : BaseAccessClass
         {
             public string Middle_Name { get; set; }
             public string Gender { get; set; }
         }
    }
}

Home.cs

public ActionResult AbsAssClass(GeneralAssClass GenAss)
{  
    Access1 ass1 = new Access1()
    {
        F_Name = GenAss. // HereI'im getting Equal, GetHash, Gettype, Tostring why not my class names("AccessClass2 ","AccessClass1")
    };
    Access2 ass2 = new Access2()
    {

    };
    return View();
}

There's two issues here.

Firstly you seem to be misusing inner classes.

Inner classes should only ever be used inside the outer class that declares them, so they should always be private.

Why/when should you use nested classes in .net? Or shouldn't you?

If you want the class to be accessible outside of the outer class then it should be a normal class, and not an inner class.

Secondly you're misusing the object initialisation syntax.

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.

Access1 ass1 = new Access1()
{
    F_Name = GenAss. // HereI'im getting Equal, GetHash, Gettype, Tostring why not my class names("AccessClass2 ","AccessClass1")
};

The bit between the braces, { and }, allows you to set the fields and properties on the ass1 instance.

It's the same as writing:

Access1 ass1 = new Access1();
ass1.F_Name = GenAss. // HereI'im getting Equal, GetHash, Gettype, Tostring why not my class names("AccessClass2 ","AccessClass1")

GenAss doesn't exist in this scope, so you can't access it.

To fix this mess you should read up on the features you're using, research the best practices for them, and then restructure your code so that it follows those best practices, and most importantly ... works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM