我如何公开我的虚空在任何地方使用

时间:2018-12-26 10:13:25

标签: c# forms datetime void public

public void Tarih()
{
     var baslangicTarih = DateTime.Today.AddDays(-20).Add(new TimeSpan(0, 0, 0));
     DateTime bitisTarih = DateTime.Now.Date.Add(new TimeSpan(0, 0, 0));
     TimeSpan Sonuc = bitisTarih - baslangicTarih;
}

但是当我尝试在另一个这样的空位上使用“ baslangicTarih”时:

Btn1_Click
    if (result.StartDate!= null)
    {
        baslangicTarih = result.StartDate;
        bitisTarih = result.EndDate;
    }

上面写着“ CS0103 C#名称在当前上下文中不存在”。

如何在另一个空白(不添加类)上使用baslangicTarihbitisTarih

2 个答案:

答案 0 :(得分:1)

因为您已在该方法范围内定义了这些变量,并且无法在该方法外部访问它们。您需要为此的类级别字段。例如:

public class MyClass
{
   // now variables are at class level scope
   // all methods can access them now
   DateTime baslangicTarih;
   DateTime bitisTarih;

  public void MethodA()
  {
     baslangicTarih = DateTime.Now;
     bitisTarih = DateTime.Now;

  }

  public void MethodB()
  {
     baslangicTarih = DateTime.Now;
     bitisTarih = DateTime.Now;
  } 
}

答案 1 :(得分:0)

变量在上下文方法中可用。要访问任何地方,请在类中声明它们

public class MyClass
{
     public DateTime baslangicTarih ;
     public DateTime bitisTarih;

     public void MyMethod()
     {

         if (result.StartDate!= null)
         {
             this.baslangicTarih = result.StartDate;
             this.bitisTarih = result.EndDate;
         }