加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么我不能在C#中创建一个object = bool?

发布时间:2020-12-16 01:54:10 所属栏目:百科 来源:网络整理
导读:我有一个程序,我试图扩展对象类,以允许一个引用数组的所有成员的方法. ExtendedArray类的代码: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleMaze{ class ExtendedArray : Object { private objec
我有一个程序,我试图扩展对象类,以允许一个引用数组的所有成员的方法.

ExtendedArray类的代码:

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

namespace ConsoleMaze
{
    class ExtendedArray : Object
    {
        private object[] referredTo;

        public ExtendedArray()
        {
            referredTo = null;
        }//empty constructor

        public ExtendedArray(Object[] obj)
        {
            referredTo = obj;
        }//full constructor

        public void referToAll(object changeTo)
        {
            for (int x = 0; x < referredTo.Length; x++)
            {
                referredTo[x] = changeTo;
            }

        }//referToAll(bool)

    }//ExtendedArray <== class
}

我打算在将来使用这个类并添加它,所以它非常通用.虽然当我尝试使用构造函数时它出错但不能隐式地将类型bool []转换为类型object [].

Boolean[] dirBoolArray = { curLeft,curUp,curRight,curDown };
ExtendedArray dirBool = new ExtendedArray(dirBoolArray);

解决方法

为什么你不能这样做:

class ExtendedArray<T> 
{
    private T[] referredTo;

    public ExtendedArray()
    {
        referredTo=null;
    }//empty constructor

    public ExtendedArray(T[] obj)
    {
        referredTo=obj;
    }//full constructor

    public void referToAll(T changeTo)
    {
        for(int x=0; x<referredTo.Length; x++)
        {
            referredTo[x]=changeTo;
        }

    }//referToAll(bool)

}//ExtendedArray <== class

class Program
{
    static void Main(string[] args)
    {
        ExtendedArray<bool> array=new ExtendedArray<bool>(new bool[10]);
        array.referToAll(true);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读