Waarom worden variabelen soms hermaakt?

Status
Niet open voor verdere reacties.

stevebravo

Gebruiker
Lid geworden
16 jan 2010
Berichten
156
Misschien heel simpel, maar waarom worden sommige variabelen hermaakt/gedupliceerd met een underscore zoals in dit voorbeeld?

Code:
class ShoppingCartItem
        {
            public Int32 ProductId;
            public decimal price;
            public Int32 quantity;
            public decimal total;

            //The standard, non-serialization constructor
            public ShoppingCartItem(int _productID, decimal _price, int _quantity)
            {
                  productId = _productID;
                  price = _price;
                  quantity = _quantity;
                  total = price * quantity;
            }
        }
 
Laatst bewerkt:
De variabelen worden niet opnieuw gemaakt. Er is een verschil tussen beide.

Degenen met underscore zijn eigenlijk parameters. Parameters geef je aan een methode mee zoals in jouw geval bijvoorbeeld het _productID
De parameters ,ook wel lokale variabelen, kunnen alleen in die methode gebruikt worden.
Om de gegevens ook in de rest van de class beschikbaar te stellen worden deze in globale variabelen gezet (hier dus degenen zonder underscore)
 
De variabelen worden niet opnieuw gemaakt. Er is een verschil tussen beide.

Degenen met underscore zijn eigenlijk parameters. Parameters geef je aan een methode mee zoals in jouw geval bijvoorbeeld het _productID
De parameters ,ook wel lokale variabelen, kunnen alleen in die methode gebruikt worden.
Om de gegevens ook in de rest van de class beschikbaar te stellen worden deze in globale variabelen gezet (hier dus degenen zonder underscore)

dus als ik het goed begrijp kunnen de underscored parameters alleen gebruikt worden binnen de in dit geval public Person, en niet daarbuiten..
 
Code:
class ShoppingCartItem
        { 
            public Int32 ProductId;
            public decimal price;
            public Int32 quantity;
            public decimal total;

            //The standard, non-serialization constructor
            public ShoppingCartItem(int _productID, decimal _price, int _quantity)
            { [COLOR="red"]<---- de underscore variablen zijn vanaf hier te gebruiken[/COLOR]
                  productId = _productID;
                  price = _price;
                  quantity = _quantity;
                  total = price * quantity;
             [COLOR="red"] <----------- Underscore variabelen zijn tot hier te gebruiken[/COLOR]
            }
        }
 
nu heb ik dus deze code, maar ik krijg een unhandled exception.. waarom?

Person.cs (console applicatie)

Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialize_People
{
    // A simple program that accepts a name, year, month date,
    // creates a Person object from that information, 
    // and then displays that person's age on the console.
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                // If they provide no arguments, display the last person
                Person p = Deserialize();
                Console.WriteLine(p.ToString());
            }
            else
            {
                try
                {
                    if (args.Length != 4)
                    {
                        throw new ArgumentException("You must provide four arguments.");
                    }

                    DateTime dob = new DateTime(Int32.Parse(args[1]), Int32.Parse(args[2]), Int32.Parse(args[3]));
                    Person p = new Person(args[0], dob);
                    Console.WriteLine(p.ToString());

                    Serialize(p);
                }
                catch (Exception ex)
                {
                    DisplayUsageInformation(ex.Message);
                }
            }
        }

        private static void DisplayUsageInformation(string message)
        {
            Console.WriteLine("\nERROR: Invalid parameters. " + message);
            Console.WriteLine("\nSerialize_People \"Name\" Year Month Date");
            Console.WriteLine("\nFor example:\nSerialize_People \"Tony\" 1922 11 22");
            Console.WriteLine("\nOr, run the command with no arguments to display that previous person.");
        }

        private static void Serialize(Person sp)
        {
            // Create file to save the data to
            FileStream fs = new FileStream("Person.Dat", FileMode.Create);

            // Create a BinaryFormatter object to perform the serialization
            BinaryFormatter bf = new BinaryFormatter();

            // Use the BinaryFormatter object to serialize the data to the file
            bf.Serialize(fs, sp);

            // Close the file
            fs.Close();
        }

        private static Person Deserialize()
        {
            Person dsp = new Person();

            // Open file to read the data from
            FileStream fs = new FileStream("Person.Dat", FileMode.Open);

            // Create a BinaryFormatter object to perform the deserialization
            BinaryFormatter bf = new BinaryFormatter();

            // Use the BinaryFormatter object to deserialize the data to from file
            dsp = (Person)bf.Deserialize(fs);

            // Close the file
            fs.Close();

            return dsp;
        }
    }
}

met de Person.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace Serialize_People
{
[Serializable]
class Person : ISerializable
{
public string name;
public DateTime dateOfBirth;
public int age;

public Person(string _name, DateTime _dateOfBirth)
{
name = _name;
dateOfBirth = _dateOfBirth;
CalculateAge();
}

public Person(SerializationInfo info, StreamingContext context)
{
name = info.GetString("Name");
dateOfBirth = info.GetDateTime("DOB");
CalculateAge();
}

// The following method is called during serialization
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", name);
info.AddValue("DOB", dateOfBirth);
}

public Person()
{
}

public override string ToString()
{
return name + " was born on " + dateOfBirth.ToShortDateString() + " and is " + age.ToString() + " years old.";
}

private void CalculateAge()
{
age = DateTime.Now.Year - dateOfBirth.Year;

// If they haven't had their birthday this year,
// subtract a year from their age
if (dateOfBirth.AddYears(DateTime.Now.Year - dateOfBirth.Year) > DateTime.Now)
{
age--;
}
}
}
}


ik krijg deze errormelding:

5372931580_89712ee297_b.jpg
 
Dat heeft zo te zien niet met je programmeerkunsten te maken :)

Hij kan het bestand person.dat niet vinden op locatie: d:\tutorials\oefeningen\hier nog een paar mappen\debug\

Staat dat bestand daar wel?
 
Dat heeft zo te zien niet met je programmeerkunsten te maken :)

Hij kan het bestand person.dat niet vinden op locatie: d:\tutorials\oefeningen\hier nog een paar mappen\debug\

Staat dat bestand daar wel?

jazeker.. kijk in de program.cs.. hij wordt daar gecreate:

Code:
private static void Serialize(Person sp)
        {
            // Create file to save the data to
            FileStream fs = new FileStream("Person.Dat", FileMode.Create);

            // Create a BinaryFormatter object to perform the serialization
            BinaryFormatter bf = new BinaryFormatter();

            // Use the BinaryFormatter object to serialize the data to the file
            bf.Serialize(fs, sp);

            // Close the file
            fs.Close();
        }
 
Zou ik dat eens gaan controleren of dat echt wel gebeurt, want daar loopt hij op fout.
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan