如何从另一个类继承变量?

  • 本文关键字:继承 变量 另一个 c#
  • 更新时间 :
  • 英文 :


我不知道如何从另一个类继承变量。我用 C# 编写代码并创建了两个类

第一个是奥索巴(英语。Person(有变量ime,prezime,OIB(英语姓名,姓氏,ID(,我还有另一个类Racun(英语帐户(,意思是银行账户。

类 Racun 有变量 podaci o vlasniku računa (英语账户持有人信息(、broj računa (英语账户序列号( 和 stanje računa (英语银行账户余额(。

那么 podaci o vlasniku računa (engl. account holder information( 需要有来自 Osoba 类的变量。我该怎么做?

我将向您展示我创建的两个带有代码的类。如果您注意到两个类都需要有 3 个变量,我没有在类 Racun(英语帐户(中创建第一个变量,因为第一个需要包含来自类 Osoba (engl.人(。

奥索巴.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Osoba
{
public string ime { get; set; }
public string prezime { get; set; }
public int oib { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.ime = tempIme;
this.prezime = tempPrezime;
this.oib = tempOib;
}
}
}

拉昆.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Racun
{
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(int tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
this.brojRacuna = tempbrojRacuna;
this.stanjeRacuna = tempstanjeRacuna;
}
}   
}

如果你的povr变量需要保存与Osoba中相同的信息片段,你可以povr引用Osoba的实例:

class Racun
{
public Osoba povr { get; set; }
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(Osoba tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
//etc

或者,您可以创建一个struct来保存公共信息:

namespace Vjezba6_1
{
struct PodaciOVlasnikuRacuna //i'm sure you can shorten this, but i don't know the language
{
public string ime;
public string prezime;
//other account holder information
}
}

并在您的类中使用它,如下所示:

namespace Vjezba6_1
{
class Osoba
{
public PodaciOVlasnikuRacuna podaci { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.podaci.ime = tempIme;
this.podaci.prezime = tempPrezime;
this.podaci.oib = tempOib;
}
}
}
namespace Vjezba6_1_v2
{
class Osoba
{
public Podaci povr { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.povr.ime = tempIme;
this.povr.prezime = tempPrezime;
this.povr.oib = tempOib;
}
}
}

最新更新