【问题标题】:How to do change the value in the class with the help of method in C#如何在 C# 方法的帮助下更改类中的值
【发布时间】:2017-03-30 21:49:28
【问题描述】:

我想从不同的类中调用一个对象并改变它的属性。

我想进入这个对象并进行更改。

但是当我键入点时,属性没有打开。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SINIF3 sınıf3 = new SINIF3();

//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;

            Console.ReadKey();
        }
    }
    class DEGER
    {
        public int number = 1;
    }
    class SINIF3
    {
        public object gonder(int a)
        {
            DEGER objem = new DEGER();
            DEGER objem2 = new DEGER();
            if (a == 1)
                return objem;
            else return objem2;
        }
    }
}

【问题讨论】:

  • 也许这只是示例代码,但您的SINIF3.gonder() 方法可以简化为:public DEGER gonder() { return new DEGER(); }

标签: c# object methods


【解决方案1】:

将gonder方法的返回类型从object改为DEGER。当然,您不会将 gonder 方法的结果分配给变量,因此您更改数字字段的新对象将被丢弃。

【讨论】:

    【解决方案2】:

    改变方法。

    来自公共对象gonder(int a)

    到公共 DEGER gonder(int a)

    否则你需要强制转换对象 就像是 sınıf3.((DEGER)gonder(1)).number=2;

    但是如果可以的话,你应该尽量不要返回对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2014-06-10
      • 1970-01-01
      • 2011-04-08
      • 2020-10-29
      • 2015-10-10
      • 2011-11-02
      • 2015-02-06
      相关资源
      最近更新 更多