简体   繁体   中英

Access Variables, Objects and Classes from another File -C#

I am working on a small project (with wpf). The project is kind like a library system, and you can add books with their name, author, copies and so on... The problem is, that I can't use the objects, variables and classes from the other files. The error message is : "The name "bookToAdd" does not exist in the current context."

Picture of code

namespace BookSystemLibrary
{
    //Create Class Book 
    public class Book
    {
        //Book Properties
        public string BookName { get; set; }
        public string AuthorName { get; set; }
        public string BookLender { get; set; }
        public string BookCopies { get; set; }

    }
    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        public void addBookDef_Click(object sender, RoutedEventArgs e)
        {
            //Create new Book Object
            Book bookToAdd = new Book();
            bookToAdd.BookName = bookNameInput.Text;
            bookToAdd.BookCopies = copiesInput.Text;
            bookToAdd.AuthorName = authorNameInput.Text;

            //Define JSON Objects
            dynamic BookAttributes =
            new
            {
                BookName = bookToAdd.BookName,
                AuthorName = bookToAdd.AuthorName,
                BookCopies = bookToAdd.BookCopies,
                Date = DateTime.Today
            };

            //Convert String into JSON Format
            string stringjson = JsonConvert.SerializeObject(BookAttributes);

            //Create JSON File with Content
            string pathForBook = $@"C:\Users\UserName\Documents\BookSystemLibrary\Books\{bookToAdd.BookName}.json";
            StreamWriter contentOfBook = new StreamWriter(pathForBook);
            //Write into File
            contentOfBook.Write(stringjson);
            contentOfBook.Close();

            MessageBox.Show($"{bookToAdd.BookName} added succesfully");
            
        }
    }
}

As stated by everyone else there's not enough relevant information here to help solve this problem. That said, from looking at what you've posted it looks like the code in the picture is not the same code in the snippet. The method LendBookDef_Click is not in the same scope as the snippet.

The error you are getting is due to the fact that your LendBookDef_Click method has no way of knowing anything about bookToAdd .

Here is a good explanation on the subject https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp/

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