C# 引用对象变量时将其保留为对象

C# 引用对象变量时将其保留为对象,c#,C#,我必须把这个带到一个可以处理双链接列表的程序中,但我对C#和windows窗体非常陌生。到目前为止,我有以下代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace doublelinkedtest { public class nodetoDBList { pub

我必须把这个带到一个可以处理双链接列表的程序中,但我对C#和windows窗体非常陌生。到目前为止,我有以下代码

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

namespace doublelinkedtest
{
    public class nodetoDBList
    {
        public object elements;
        public nodetoDBList prev;
        public nodetoDBList next;

        public nodetoDBList (int temp)
        {
            elements = temp;
            next = null;
        }

        public void inserToList(object elements)
        {
            nodetoDBList newLink;
            newLink = new nodetoDBList (elements);
        }
    }
}
但现在我得到了以下错误: 参数1:无法从“object”转换为“int”。 为什么我会出现这个错误?。我只是引用变量,而不是转换它


我对C#很陌生。正如你们所看到的,为了实现一个双链表项目,我正在一步一步地进行这个项目。请帮忙

您正在调用带有对象的
nodeToDBList
构造函数(它接受
int
):

public nodetoDBList (int temp) <- Constructor takes an int
{
    elements = temp;
    next = null;
}

public void inserToList(object elements)
{
    nodetoDBList newLink;
    newLink = new nodetoDBList (elements); <- passing in an object instead
}

public nodetoDBList(int-temp)您正在调用带有对象的
nodetoDBList
构造函数(它接受
int
):

public nodetoDBList (int temp) <- Constructor takes an int
{
    elements = temp;
    next = null;
}

public void inserToList(object elements)
{
    nodetoDBList newLink;
    newLink = new nodetoDBList (elements); <- passing in an object instead
}

public nodetoDBList(int-temp)构造函数无论如何都不应该使用
int
。该字段接受一个
对象
@siride-是的,我刚刚更新了我的答案以说明这一点。但是当我使elements=temp时,它会自动将元素转换为int吗?怎么会这样?因为对象{int}是类型..假设您使用调试器和QuickWatch检查变量类型。@CrisAlfie-程序不会真正将
元素
转换为
int
;它本质上是说“我所知道的
元素
就是它是一个
对象
”,尽管它在幕后实际上是一个
int
。如果您试图对代码中的
元素
执行操作,可以将其视为
对象
,也可以将其转换为
int
(这就像您告诉编译器“相信我,当程序运行时,它将是
int
)在您可以将其视为
int
之前。构造函数无论如何都不应该使用
int
。该字段接受一个
对象
@siride-是的,我刚刚更新了我的答案以说明这一点。但是当我使elements=temp时,它会自动将元素转换为int吗?怎么会这样?因为对象{int}是类型..假设您使用调试器和QuickWatch检查变量类型。@CrisAlfie-程序不会真正将
元素
转换为
int
;它本质上是说“我所知道的
元素
就是它是一个
对象
”,尽管它在幕后实际上是一个
int
。如果您试图对代码中的
元素
执行操作,可以将其视为
对象
,也可以将其转换为
int
(这就像您告诉编译器“相信我,当程序运行时,它将是
int
)在将其视为
int
之前,请更改方法签名以接受
对象
作为参数,或将temp转换为
(int)temp
,或使用
this.elements=Convert.ToInt32(temp)对象
作为参数,要么将temp转换为
(int)temp
,或者使用
this.elements=Convert.ToInt32(temp);
为什么否决?我提出了一个完全有效的问题-”