【问题标题】:Do you have your own 'utils' dll and what do you keep there?你有自己的 'utils' dll 吗?你在那里保留什么?
【发布时间】:2008-11-26 00:11:27
【问题描述】:

我可以从我自己的 .NET dll 开始。我有一个我在所有网络项目(大约 10 个)中使用的 dll,并且我有用于 FTP、zip、imageresizing、extensionmethods 的 util 类和一个通用的单例类。

我认为这是一种常见的做法,我只是觉得听听人们在他们的“Utils”dll 中放了什么会很有趣

编辑: 您有哪些小代码 gem 可以让您使用更少的代码提高工作效率?

在放入数据库之前解析可为空的表单输入时,这些扩展方法对我非常有用

        public static int? ToInt(this string input) 
        {
            int val;
            if (int.TryParse(input, out val))
                return val;
            return null;
        }

        public static DateTime? ToDate(this string input)
        {
            DateTime val;
            if (DateTime.TryParse(input, out val))
                return val;
            return null;
        }

        public static decimal? ToDecimal(this string input)
        {
            decimal val;
            if (decimal.TryParse(input, out val))
                return val;
            return null;
        }

【问题讨论】:

    标签: c# .net dll


    【解决方案1】:

    我认为在当前版本的语言之外携带实用程序集弊大于利。

    主要原因是随着语言的发展,内置了新的方法和更好的做事方式。通过携带实用程序程序集,您很快就会遇到大量可能暴露安全问题的自重。

    一个典型的例子是提升函数列表。快速浏览一下就会发现 .Net(就像大多数其他语言一样)已经覆盖了至少 75% 的代码。

    【讨论】:

    • 这很好,如果我的代码的内置版本随下一个 .net 库一起提供,我总是尝试删除或升级我的 Utils dll,但我也认为很多人的代码可以成为下一个 .net 框架的候选者,看到这样的例子会很有趣。
    • 这是一个很好的观点。如果我正在做的工作与.NET 相关,我肯定会为了我认为最好的东西而折腾我的东西。然而,就我而言,.NET 太容易被反编译(使其成为一种替代开源),我的雇主希望保护他的知识产权。
    • 任何东西都可以逆向工程。你所能做的就是努力让它变得困难,这就是混淆的全部意义,以及为什么在 .net 和 java 之前的那个时代就可以使用专业产品。
    【解决方案2】:

    我多年来一直在收集。这开始是a set of VBScript routines,我已经转换为VB6。这是一个 COM DLL,所以我几乎可以在几乎任何语言的任何地方使用它。我已经让你免去了所有枚举的无聊。

    编辑:我原则上同意 Chris Lively 对本节先前帖子的评论。然而,正如我在 cmets 中所说,如果我正在做的工作与 .NET 相关,我肯定会为了我认为最好的东西而折腾我的东西。然而,就我而言,.NET 太容易被反编译(使其成为一种替代开源),我的雇主希望保护他的知识产权。

    (Autogenerated by TLViewer, © Mark Pryor 2000-2003) 
    
    Library: Std
        P:\other\StdLib\StdLib.dll 
        Description: Std 
    
    coclass Drives
    
    Function DriveType(ByVal sDrv As String) As String
    
    
    coclass Arrays
    
    Function AAdd(aToThis ,ByVal xAddThis ) As Integer
    
    Function AAdd_PostIncrement(a , ByVal X ) As Variant
    
    Function AAdd_PreIncrement(a , ByVal X ) As Variant
    
    Function AMax(aVec ) As Variant
    
    Function AMin(aVec ) As Variant
    
    Sub DeleteFirst(anArray )
    
    Sub DeleteLast(anArray )
    
    Sub DeleteNth(anArray , ByVal nElement As Long)
    
    Function GenerateRange(nBot As Double, nTop As Double, [nStep As Double = 1]) As Variant
    
    Function GenerateRangeFromString(sRange ) As Variant
    
    Function InArray(sItem , aList ) As Boolean
    
    Function Reverse1DArray(aInput ) As Variant
    
    Function ShowStructure(vToShow ) As String
    
    Function StrInArray(sItem , aList , [bCaseInsens As Boolean = True]) As String
    
    
    coclass CmdLine
    
    Property AppExeName([BaseOnly As Boolean = False]) As String [Get/o]
    
    Property AppPath As String [Get/o]
    
    Property Argument(ByVal Which As Long) As String [Get/o]
    
    Property Arguments As Long [Get/o]
    
    Property CaseSensitive As Boolean [Get/Let]
    
    Function FlaggedArg(ByVal Flag As String) As String
    
    Function FlagPresent(ByVal Flag As String) As Long
    
    Function FlagPresentFromList(Flags () As Variant) As Boolean
    
    Sub Refresh()
    
    Function ToString() As String
    
    
    coclass BigString
    
    Sub ClearStr()
    
    Function GetStr([ByVal vJoiner = ]) As String
    
    Function GetStrArray() As Variant
    
    Sub PutStr(ByVal vString )
    
    
    coclass Config
    
    Sub Define(sKey , sValue )
    
    Property gsFilename As String [Get/Let]
    
    Function List(sFilter ) As String
    
    Function Load(sFile ) As Boolean
    
    Function LoadW(sFile ) As Boolean
    
    Function Recall(sKey ) As Variant
    
    Function RecallElse(sKey , sDefault ) As Variant
    
    Sub Save([sFile = ], [bAsAnsi = False])
    
    Sub SaveW([sFile = ], [bAsAnsi = False])
    
    
    coclass Collections
    
    Function Add(vData , [sKey ]) As _Variable 
    
    Property AddOnly As Boolean [Get/Let]
    
    Function Count() As Long
    
    Function Exists(vntIndexKey ) As Boolean
    
    Property Item(vntIndexKey ) As _Variable  [Get/o]
    
    Function Items() As Variant
    
    Function Keys() As Variant
    
    Sub Modify(sValue , sKey )
    
    Property NewEnum As stdole.IUnknown  [Get/o]
    
    Sub Remove(vntIndexKey )
    
    
    coclass Computers
    
    Function ComputerName() As String
    
    Function ExistsFolder(sComputer As String, sDir As String) As Boolean
    
    Function GetComputers(sDomain As String)() As Variant
    
    Function GetDomainComputers(ByVal strDomain As String)() As Variant
    
    Function GetNBT(sComputer As String) As String
    
    Function GetNBTA(sIPAddr As String) As String
    
    Function GetNetView(sDomain As String) As String
    
    Function GetOnlineComputers(sDomain As String)() As Variant
    
    Function GetRemoteEnvironment(sComputer )() As Variant
    
    Function GetSpecs(sComputer As String) As String
    
    Function GetTheComputerName() As String
    
    Function ResolveIP(sName As String) As String
    
    
    coclass Logic
    
    Function IIF(bCondition As Boolean, vTrue , vFalse ) As Variant
    
    
    coclass Decimals
    
    Property Dec As Variant [Get/Let]
    
    
    coclass Domains
    
    Function GetAvailableNTDomains()() As Variant
    
    
    coclass Database
    
    Sub CreateDatabase(sFile As String)
    
    Sub CreateIndex(ByVal oDb  As ADODB.Connection, sSpec As String)
    
    Sub CreateStructure(ByVal oDb  As ADODB.Connection, sSpec As String)
    
    Function OpenDatabase(theFile As String) As ADODB._Connection 
    
    Function OpenRecordSet(ByVal oDb  As ADODB.Connection, sQuery As String) As ADODB._Recordset 
    
    
    coclass DateTime
    
    Function dbDate(vDate ) As String
    
    Function GetGmtTime([StartingDate ]) As Date
    
    Function GetTimeDifference() As Long
    
    Function GetTimeHere(gmtTime As Date) As Date
    
    Function InternetTimeToVbLocalTime(ByVal DateString As String) As Date
    
    
    coclass Wallpaper
    
    Function ActiveDesktopSetWallpaper(ByVal strFile As String) As Boolean
    
    Sub At(ByVal nX As Integer, ByVal nY As Integer)
    
    Sub AtSay(ByVal nX As Integer, ByVal nY As Integer, ByVal sText As String)
    
    Sub Attributes(ByVal sAttribList As String)
    
    Sub Colour(ByVal iFGColour As Long, ByVal iBGColour As Long)
    
    Sub Dimensions(ByVal nHeight As Integer, ByVal nWidth As Integer)
    
    Sub Font(ByVal sName As String, ByVal iSize As Integer)
    
    Function LoadPic(sFilename As String, [nDestX As Integer = ], [nDestY As Integer = ]) As Variant
    
    Property Picture As Object [Get/Set]
    
    Sub SavePic(sFilename As String, [iType As Integer = 1])
    
    Sub Say(ByVal sText As String)
    
    Sub ScaleMode(ByVal iMode As Integer)
    
    Function TextHeight(ByVal sText As String) As Integer
    
    Function TextWidth(ByVal sText As String) As Integer
    
    
    coclass Excel
    
    Sub ExcelColumnNames(aHeadings () As Variant, [bBold As Boolean = True])
    
    Sub ExcelNewSheet()
    
    Sub ExcelStart([bHidden As Boolean = False])
    
    
    coclass StopWatch
    
    Sub Finish()
    
    Function FinishTime() As Date
    
    Function LapTime() As String
    
    Function Seconds() As Integer
    
    Sub Start()
    
    Function StartTime() As Date
    
    
    coclass Environments
    
    Function GetProcessEnv(strEnvVar As String) As String
    
    Function GetSystemEnv(strEnvVar As String) As String
    
    Function GetUserEnv(strEnvVar As String) As String
    
    Function GetVolatileEnv(strEnvVar As String) As String
    
    
    coclass Schedule
    
    Function AddTask(strTime , strCommand , [enDaysInWeek As ENUM_WEEKDAYS  = ], [strDaysInMonth = ], [RunInteractive As Boolean = True], [ReOccuring As Boolean = True]) As Long
    
    Function DeleteTask(lngID As Long) As Boolean
    
    Function GetNameOfComputer() As String
    
    
    coclass SymbolTable
    
    Function Append(sName , sValue ) As String
    
    Sub Clear()
    
    Function Increment(sName ) As Integer
    
    Function IsSym(sName ) As Boolean
    
    Function Keys()() As Variant
    
    Sub Parse(sData , sSep )
    
    Function Recall(sName ) As Variant
    
    Sub Remove(sData )
    
    Sub Store(sName , vValue )
    
    Sub StoreDup(sName , xValue )
    
    Sub StoreDup2(sName , xValue )
    
    Function SymList() As Variant
    
    Function SymListText() As String
    
    
    coclass Files
    
    Function CollectFiles(sDirectory , sFileType ) As Variant
    
    Sub DeleteFile(ByVal cFilename )
    
    Function Exists(sFile ) As Boolean
    
    Function FileHasBeenModified(sFile As String, dThen As Date) As Boolean
    
    Function FileModificationDate(sFile As String) As Date
    
    Function IsUTF16LE(sFile As String) As Boolean
    
    Function RandomInputFile(sExt As String) As String
    
    Function RandomOutputFile(sRandomInputFile As String, sExt As String) As String
    
    Function ReadFileA(FileName ) As String
    
    Function ReadFileE(FileName ) As String
    
    Function ReadFileU(FileName ) As String
    
    Function ReadFirstLineA(FileName ) As Variant
    
    Function ReadFirstLineE(FileName ) As String
    
    Function ReadFirstLineU(FileName ) As String
    
    Sub WriteFileA(sFilename , sContents , nMode As Long)
    
    Sub WriteFileB(sFilename , nOffset As Long, vData )
    
    Sub WriteFileU(sFilename , sContents , nMode As Long)
    
    
    coclass System
    
    Function AvailableDesktopDimensions() As Variant
    
    Function CaptureDOS(sCommand , [bSynch As Boolean = True]) As Variant
    
    Function ConsoleWrite(sText As String) As Long
    
    Function ConsoleWriteLine(sText As String) As Long
    
    Function CreateGUID() As String
    
    Function DesktopDimensions() As Variant
    
    Function DoEventsSeconds(nSeconds As Integer) As Integer
    
    Sub DoEventsSeconds2(iSeconds As Integer)
    
    Function GetTheWindowsDirectory() As String
    
    Function GetUUID(sUuid As String) As Boolean
    
    Function KillProcess(ProcessName As String) As Boolean
    
    Sub Navigate(ByVal NavTo As String)
    
    Function SetProcessPriority(sProcess As String, nPriority As EPROCESS_PRIORITY ) As Boolean
    
    Function ShellEx(ByVal sFile As String, [eShowCmd As EShellShowConstants  = essSW_SHOWDEFAULT], [ByVal sParameters As String = ], [ByVal sDefaultDir As String = ], [sOperation As String = "open"], [Owner As Long = ]) As Boolean
    
    Sub Sleep(nMilli As Integer)
    
    Function SystemDefaultUILanguage() As Long
    
    Function ThreadLocale() As Long
    
    
    coclass Groups
    
    Function GetComputerGroups(ByVal strComputerName As String)() As Variant
    
    Function GetDefaultNamingContext() As String
    
    Function GetGroups()() As Variant
    
    
    coclass Help
    
    Function HHDisplayHeadTopic(ByVal lHwnd As Long) As Long
    
    Function HHDisplaySearch(ByVal lHwnd As Long, [toSearch As String = ]) As Long
    
    Function HHHelpContents(ByVal lHwnd As Long) As Long
    
    Function HHHelpIndex(ByVal lHwnd As Long, [toSearch As String = ]) As Long
    
    Sub HHInitialize()
    
    Function HHKeywordLookup(ByVal lHwnd As Long, [sKeyword As String = ]) As Long
    
    Sub HHUninitialize()
    
    Property sHelpFile As String [Get/Let]
    
    
    coclass Number
    
    Function IntegerToUnsigned(Value As Integer) As Long
    
    Function LongToUnsigned(Value As Long) As Double
    
    Function UnsignedToInteger(Value As Long) As Integer
    
    Function UnsignedToLong(Value As Double) As Long
    
    
    coclass IEDisplay
    
    Sub Display(sMsg As String, nMillisec As Integer)
    
    Sub Init(sPosition )
    
    Property sName As String [Get/Let]
    
    
    coclass Temp
    
    Function GetTempFileName([sSeed As String = ]) As String
    
    Function LocGetFilePath(ByVal iCFName As String) As String
    
    Function TempDir() As String
    
    Function TempDirWide() As String
    
    Function TempFile(Create As Boolean, [lpPrefixString ], [lpszPath ]) As String
    
    Function UnicodeTempFile(ByVal iFileName As String) As String
    
    
    coclass INI
    
    Sub Clear()
    
    Function GetValue(sSection As String, sKey As String, strDefault As String) As String
    
    Function HasSection(sSection As String) As Boolean
    
    Function Load(sIniName As String) As Boolean
    
    Function ReadINIA(sSection , sKeyName , sINIFileName ) As String
    
    Function ReadINIU(sSection As String, sKeyName As String, sINIFileName As String) As String
    
    Function WriteINIA(sSection , sKeyName , sNewString , sINIFileName ) As Boolean
    
    Function WriteINIU(sSection As String, sKeyName As String, sNewString As String, sINIFileName As String) As Boolean
    
    
    coclass Variable
    
    Property Name As Variant [Get/Let/Set]
    
    Property Value As Variant [Get/Let/Set]
    
    
    coclass Mouse
    
    Function Between(ByVal nNumber As Integer, ByVal nLowerBound As Integer, ByVal nUpperBound As Integer) As Boolean
    
    Function MouseX([ByVal hWnd As Long = ]) As Long
    
    Function MouseY([ByVal hWnd As Long = ]) As Long
    
    
    coclass Traces
    
    Sub ClearTrace()
    
    Sub Trace([ByVal sTag = "!@#$%^&*()_"])
    
    Property TraceFile As String [Get/Let]
    
    Property Tracing As Boolean [Get/Let]
    
    
    coclass Registry
    
    Property ClassKey As ERegistryClassConstants  [Get/Let]
    
    Sub CreateAdditionalEXEAssociations(ByVal sClassName As String, vItems () As Variant)
    
    Sub CreateEXEAssociation(ByVal sExePath As String, ByVal sClassName As String, ByVal sClassDescription As String, ByVal sAssociation As String, [ByVal sOpenMenuText As String = "&Open"], [ByVal bSupportPrint As Boolean = False], [ByVal sPrintMenuText As String = "&Print"], [ByVal bSupportNew As Boolean = False], [ByVal sNewMenuText As String = "&New"], [ByVal bSupportInstall As Boolean = False], [ByVal sInstallMenuText As String = ], [ByVal lDefaultIconIndex As Long = -1])
    
    Function CreateKey() As Boolean
    
    Property Default As Variant [Get/Let]
    
    Function DeleteKey() As Boolean
    
    Function DeleteValue() As Boolean
    
    Function EnumerateSections(sSect () As String, iSectCount As Long) As Boolean
    
    Function EnumerateValues(sKeyNames () As String, iKeyCount As Long) As Boolean
    
    Property KeyExists As Boolean [Get/o]
    
    Property Machine As String [Get/Let]
    
    Property SectionKey As String [Get/Let]
    
    Property Value As Variant [Get/Let]
    
    Property ValueEx(ClassKey As ERegistryClassConstants , SectionKey As String, ValueKey As String, ValueType As ERegistryValueTypes , Default ) As Variant [Get/Let]
    
    Property ValueKey As String [Get/Let]
    
    Property ValueType As ERegistryValueTypes  [Get/Let]
    
    
    coclass Users
    
    Function GetComputerUsers(ByVal strComputerName As String)() As Variant
    
    Function GetComputerUsers2(ByVal strComputerName )() As Variant
    
    Function GetDomainUser(sComputer As String) As String
    
    Function GetLoginProfiles(sComputer )() As Variant
    
    Function GetMac(sDevice ) As String
    
    Function GetNameAndDescription(spDomain As String, sUsername As String) As String
    
    Function GetOUofUser(sDomain As String, sUsername As String) As String
    
    
    coclass Sort
    
    Sub heapsort(aVec )
    
    Sub quicksort(aVec )
    
    Sub shellsort(a0 , [bAscending As Boolean = True])
    
    Sub shellSortOnField(aVec , ByVal nField As Integer, ByVal sFieldSep , [nComparisonType As SSOF_COMPARISON  = SSOF_NUMERICAL])
    
    Function sorted()() As Variant
    
    
    coclass Strings
    
    Function AnyOf(sText , nOperator As AO_COMPARATORS , sChar ) As Boolean
    
    Function AnyOfList(sText , nOperator As AO_COMPARATORS , aChar ) As Boolean
    
    Function AsString(X ) As String
    
    Function BeginsWith(sText , sBeginning , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function Between(sText , sBegin , sEnd ) As String
    
    Function ByteArrayToString(aBytes () As Byte) As String
    
    Function ComprehendCSV(sText ) As Variant
    
    Function Contains(sText , sChunk , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function CountFields(strText , strDelim ) As Integer
    
    Function DQ(s ) As String
    
    Function EndsWith(sText , sEnding , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function EndsWithSet(sText , vEnding , [bCaseInsensitive As Boolean = True]) As Boolean
    
    Function FirstLineOf(sData ) As String
    
    Function FirstWord(sText ) As String
    
    Function ForceExtension(sFilename , sExtension ) As String
    
    Function HexDump(sData ) As String
    
    Function HTMLWrap(sTag , sContent ) As String
    
    Function LastLineOf(sData ) As String
    
    Function LeftFill(sText , nLen , sFill ) As String
    
    Function LeftOf(sText , sItem ) As String
    
    Function LeftOfLast(sText , sItem ) As String
    
    Function NthField(sText , sDelimiter , nReqdField ) As String
    
    Function NthLineOf(n As Integer, sData ) As String
    
    Function RemoveSpaces(sText ) As String
    
    Function Reverse(sText ) As String
    
    Function RightFill(sText , nLen , sFill ) As String
    
    Function RightOf(sText , sItem ) As String
    
    Function RightOfLast(sText , sItem ) As String
    
    Function SplitSet(ByVal sString , ByVal sSet ) As Variant
    
    Function StringConversion(s , n As Integer) As String
    
    Function StringMap(sText , aFrom , vTo ) As String
    
    Function StringToByteArray(ByVal sString )() As Byte
    
    Function Subst(sText , paArgList () As Variant) As String
    
    Function Subst2(sText , paArgList () As Variant) As String
    
    Function ZeroFill(nNum , nWidth ) As String
    
    Function Zerofill2(nNum ) As String
    

    【讨论】:

      【解决方案3】:

      我才刚刚真正开始我的,但目前它主要包含我一直使用的常见扩展方法。像“ThrowIfNull()”这样的东西,所以我不必每次要检查空值时都做大量的 if 语句。

      我还有一个游乐场项目,里面有我正在玩弄的任何想法,但我不能 100% 确定它们是否会奏效。

      【讨论】:

      • 只是一个观察,但是当简单地尝试访问空对象的成员会自动抛出异常时,为什么还要打扰 ThrowIfNull() 呢?
      • 它主要是为了让我可以抛出任何我想要的异常,如果成员为 null 并带有自定义消息,而不是让它继续,然后抛出一个没有描述的 argunullexception。
      【解决方案4】:

      我按功能对实用程序进行分组。因此,我没有 one 实用程序 DLL,而是一个包含多个此类程序集的文件夹,每个程序集都封装一个任务(通常包括不止一个类,实际上它通常包括一个整个层次结构)。

      在极端情况下,这意味着我有一个包含一个声明的 DLL,即以下声明(加上文档):

      namespace madrat.Common {
          public interface ICopyable<T> {
              T Copy();
          }
      }
      

      请注意,与System.ICloneable 接口不同,此接口具有文档中指定的明确定义的语义(深拷贝)。

      那么为什么要为这个微小的声明添加一个额外的 DLL?因为它使其他程序集之间的互操作性变得更加容易。

      【讨论】:

        【解决方案5】:

        这是我个人库中的两个课程。它让事情变得更好:)

        public class DynamicArray<Type>
        {
            private Type[] internalArray;
        
            public DynamicArray()
            {
                internalArray = new Type[0];
            }
        
            public int Length
            {
                get
                {
                    return internalArray.Length;
                }
                set
                {
                    if (value >= 0)
                        Array.Resize<Type>(ref internalArray, value);
                    else
                        throw new ArgumentOutOfRangeException
                        ("Length can not be less than zero!");
                }
            }
        
            public Type[] AsNormalArray
            {
                get
                {
                    return internalArray;
                }
                set
                {
                    internalArray = value;
                }
            }
        
            public Type this[int index]
            {
                get
                {
                    if (index >= 0 && index < internalArray.Length)
                        return internalArray[index];
                    else
                        throw new IndexOutOfRangeException
                        ("Index was outside the bounds of the array!");
                }
                set
                {
                    //Get error handling out of the way first
                    if (index < 0)
                        throw new IndexOutOfRangeException
                        ("Index must be greater than or equal to zero!");
                    //I decided that being able to grow by any amount can eventually lead
                    //to lots of bugs, think about it. Just set the length manually
                    //by assigning to .Length :)
                    if (index > internalArray.Length)
                        throw new IndexOutOfRangeException
                        ("Can not dynamically grow more than one element at a time! Set length manually.");
                    //We are left with two possibilities. A. we are indexing an existing element or
                    //B. we are indexing one element to high (same as length, big array no no)
                    //so grow an element
                    if (index < internalArray.Length)//Then we dont need to grow an element
                    {
                        internalArray[index] = value;
                    }
                    else//Then grow one element, and add the value
                    {
                        Array.Resize<Type>(ref internalArray, internalArray.Length + 1);
                        internalArray[index] = value;
                    }
                }
            }
        
            public void Add(params Type[] values)
            {
                int start = internalArray.Length; //Start adding values at the end
                this.Length += values.Length; //Pre-set length (faster)
        
                foreach (Type val in values)
                {
                    //this[start++] = val; Possibly slower
                    internalArray[start++] = val;
                }
            }
        
            public int IndexOf(Type thisValue)
            {
                int i = 0;
                bool found = false;
        
                for(; i <= internalArray.Length; i++)
                {
                    if(internalArray[i].Equals(thisValue))
                    {
                        found = true;
                        break;
                    }
                }
        
                if(found)
                    return i;
                else
                    throw new ArgumentException
                    (thisValue+" does not exist!");
            }
        
            public bool Contains(Type thisValue)
            {
                bool found = false;
        
                foreach (Type val in internalArray)
                {
                    if (val.Equals(thisValue))
                    {
                        found = true;
                        break;
                    }
                }
        
                return found;
            }
        }
        
        
        
        public class AssosiativeArray<ArrayT, KeyT>
        {
            //Easy peasy lemon squeezy
            private DynamicArray<ArrayT> values;
            private DynamicArray<KeyT> keys;
        
            public AssosiativeArray()
            {
                values = new DynamicArray<ArrayT>();
                keys = new DynamicArray<KeyT>();
            }
        
            public int Length
            {
                get
                {
                    return values.Length;
                }
            }
        
            public ArrayT[] ValuesAsNormalArray
            {
                get
                {
                    return values.AsNormalArray;
                }
            }
        
            public KeyT[] KeysAsNormalArray
            {
                get
                {
                    return keys.AsNormalArray;
                }
            }
        
            public ArrayT this[KeyT index]
            {
                get
                {
                    if (keys.Contains(index))
                    {
                        return values[keys.IndexOf(index)];
                    }
                    else
                    {
                        throw new ArgumentException
                        ("The key "+index+" does not exist!");
                    }
                }
                set
                {
                    keys[keys.Length++] = index;
                    values[values.Length++] = value;
                }
            }
        
            public bool ContainsKey(KeyT key)
            {
                bool found = false;
        
                foreach (KeyT val in keys.AsNormalArray)
                {
                    if (val.Equals(key))
                    {
                        found = true;
                        break;
                    }
                }
        
                return found;
            }
        }
        

        }

        【讨论】:

          猜你喜欢
          • 2021-05-01
          • 2010-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-15
          相关资源
          最近更新 更多