首页 > 开发 > 综合 > 正文

HOW TO:配置或数据文件的保存(改进)

2024-07-21 02:29:17
字体:
来源:转载
供稿:网友
  • 网站运营seo文章大全
  • 提供全面的站长运营经验及seo技术!
  •   how to:配置或数据文件的保存 这个原是基于net2003,其中又用了2005的泛型(of tconfiginformation),显得不伦不类。现在改为2005的,并取消了接口的引入。

    序列化类:

    public class serializehelperclass serializehelper(of t)

        private sub new()sub new()
        end sub

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared function itemtoxml()function itemtoxml(byval obj as t) as string
            dim mresult as string = ""
            dim mserializer as new system.xml.serialization.xmlserializer(gettype(t))
            dim mstringwriter as new system.io.stringwriter
            using mstringwriter
                mserializer.serialize(mstringwriter, obj)
                mresult = mstringwriter.tostring
                mstringwriter.close()
            end using
            return mresult
        end function

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared function xmltoitem()function xmltoitem(byval xml as string) as t
            dim mserializer as new system.xml.serialization.xmlserializer(gettype(t))
            dim mstringreader as new system.io.stringreader(xml)
            return ctype(mserializer.deserialize(mstringreader), t)
        end function

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared sub itemtoxmlfile()sub itemtoxmlfile(byval filename as string, byval obj as t)
            dim xmlwriter as new system.io.streamwriter(filename, false)
            using xmlwriter
                xmlwriter.write(itemtoxml(obj))
                xmlwriter.close()
            end using
        end sub

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared function xmlfiletoitem()function xmlfiletoitem(byval filename as string) as t
            dim xmlreader as new system.io.streamreader(filename, system.text.encoding.default)
            dim mobj as t
            using xmlreader
                mobj = xmltoitem(xmlreader.readtoend)
                xmlreader.close()
            end using
            return mobj
        end function

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared sub itemtoformatterfile()sub itemtoformatterfile(byval filename as string, byval formatter as system.runtime.serialization.iformatter, byval obj as t)
            dim mfilestream as system.io.stream = system.io.file.open(filename, system.io.filemode.create)
            using mfilestream
                formatter.serialize(mfilestream, obj)
                mfilestream.close()
            end using
        end sub

        <system.componentmodel.editorbrowsable(componentmodel.editorbrowsablestate.advanced)> _
        public shared function formatterfiletoitem()function formatterfiletoitem(byval filename as string, byval formatter as system.runtime.serialization.iformatter) as t
            dim mfilestream as system.io.stream = system.io.file.open(filename, system.io.filemode.open)
            dim mobj as t
            using mfilestream
                mobj = ctype(formatter.deserialize(mfilestream), t)
                mfilestream.close()
            end using
            return mobj
        end function

        public shared function clone()function clone(byval obj as t) as t
            dim tmpt as t
            dim mformatter as new system.runtime.serialization.formatters.binary.binaryformatter
            dim mmemorystream as new system.io.memorystream
            using mmemorystream
                mformatter.serialize(mmemorystream, obj)
                mmemorystream.position = 0
                tmpt = ctype(mformatter.deserialize(mmemorystream), t)
                mmemorystream.close()
            end using
            return tmpt
        end function

        public shared sub save()sub save(byval filename as string, byval formattype as formattype, byval obj as t)
            select case formattype
                case formattype.binary
                    itemtoformatterfile(filename, new system.runtime.serialization.formatters.binary.binaryformatter, obj)
                case formattype.soap
                    itemtoformatterfile(filename, new system.runtime.serialization.formatters.soap.soapformatter, obj)
                case formattype.xml
                    itemtoxmlfile(filename, obj)
            end select
        end sub

        public shared function load()function load(byval filename as string, byval formattype as formattype) as t
            select case formattype
                case formattype.binary
                    return formatterfiletoitem(filename, new system.runtime.serialization.formatters.binary.binaryformatter)
                case formattype.soap
                    return formatterfiletoitem(filename, new system.runtime.serialization.formatters.soap.soapformatter)
                case formattype.xml
                    return xmlfiletoitem(filename)
            end select
            return nothing
        end function

    end class

    public enum formattypeenum formattype
        xml
        binary
        soap
    end enum

    配置与数据文件处理类:

        public mustinherit class configinformationcollectionbaseclass configinformationcollectionbase(of tkey, tvalue)
            inherits system.collections.generic.dictionary(of tkey, tvalue)

            '默认为formattype.binary
            private gformattype as lzmtw.formattype = lzmtw.formattype.binary
            private gfilename as string = appdomain.currentdomain.basedirectory & "{0}.dat"

            public sub read()sub read()
                read(gformattype)
            end sub

            public sub read()sub read(byval formattype as lzmtw.formattype)
                gfilename = string.format(gfilename, gettype(tvalue).name)
                read(gfilename, formattype)
            end sub

            public sub read()sub read(byval file as string, byval formattype as lzmtw.formattype)
                gfilename = file
                gformattype = formattype
                me.load()
            end sub

            public shadows sub add()sub add(byval item as tvalue)
                dim mkeyvalue as tkey = nothing
                if keynameisfield() then
                    mkeyvalue = ctype(gettype(tvalue).getfield(keyname).getvalue(item), tkey)
                else
                    mkeyvalue = ctype(gettype(tvalue).getproperty(keyname).getvalue(item, nothing), tkey)
                end if

                if not me.containskey(mkeyvalue) then
                    '不存在,增加记录
                    mybase.add(mkeyvalue, item)
                else
                    '存在,作修改处理
                    me.item(mkeyvalue) = item
                end if
            end sub

            public sub save()sub save()
                dim mitems(me.count - 1) as tvalue
                me.values.copyto(mitems, 0)
                serializehelper(of tvalue()).save(gfilename, gformattype, mitems)
            end sub

            private sub load()sub load()
                if not io.file.exists(gfilename) then
                    initialize()
                    save()
                else
                    dim mitems() as tvalue
                    mitems = ctype(serializehelper(of tvalue()).load(gfilename, gformattype), tvalue())
                    for each item as tvalue in mitems
                        me.add(item)
                    next
                end if
            end sub

            ''' <summary>
            ''' '继承时,若有初始赋值,在此实现
            ''' </summary>
            protected mustoverride sub initialize()sub initialize()

            ''' <summary>
            ''' 指定tvalue的键名(字段或属性)的名称
            ''' </summary>
            protected mustoverride readonly property keyname()property keyname() as string

            ''' <summary>
            ''' 指定tvalue的键名是字段(真)还是属性(假)
            ''' </summary>
            protected mustoverride readonly property keynameisfield()property keynameisfield() as boolean

            sub new()sub new()
                '检测键名是否有效,键名的类和tkey是否相符
                if keynameisfield() then
                    dim mfieldinfo as reflection.fieldinfo = gettype(tvalue).getfield(keyname)
                    if mfieldinfo is nothing then
                        throw new systemexception(string.format("类{0}中不存在名称为{1}的字段", gettype(tvalue).name, keyname))
                    else
                        if not mfieldinfo.fieldtype.name.equals(gettype(tkey).name) then
                            throw new systemexception(string.format("类{0}中字段名称为{1}的类型为{2},与指定的键值类型{3}不符", gettype(tvalue).name, keyname, mfieldinfo.fieldtype.name, gettype(tkey).name))
                        end if
                    end if
                else
                    dim mpropertyinfo as reflection.propertyinfo = gettype(tvalue).getproperty(keyname)
                    if mpropertyinfo is nothing then
                        throw new systemexception(string.format("类{0}中不存在名称为{1}的属性", gettype(tvalue).name, keyname))
                    else
                        if not mpropertyinfo.propertytype.name.equals(gettype(tkey).name) then
                            throw new systemexception(string.format("类{0}中属性名称为{1}的类型为{2},与指定的键值类型{3}不符", gettype(tvalue).name, keyname, mpropertyinfo.propertytype.name, gettype(tkey).name))
                        end if
                    end if
                end if

            end sub
        end class

    应用如下:
    1、定义配置或数据类

    <serializable()> _
    public class myconfiginfoclass myconfiginfo
        private mmachine as string
        private mlogins(-1) as login

        public property machine()property machine() as string
            get
                return mmachine
            end get
            set(byval value as string)
                mmachine = value
            end set
        end property

        public readonly property logins()property logins() as login()
            get
                return mlogins
            end get
        end property

        public sub add()sub add(byval login as login)
            redim preserve mlogins(mlogins.length)
            mlogins(mlogins.length - 1) = login
        end sub

        <serializable()> _
        public class loginclass login
            private muser as string
            private mpass as string

            public property user()property user() as string
                get
                    return muser
                end get
                set(byval value as string)
                    muser = value
                end set
            end property

            public property pass()property pass() as string
                get
                    return mpass
                end get
                set(byval value as string)
                    mpass = value
                end set
            end property

            sub new()sub new()
            end sub

            sub new()sub new(byval user as string, byval pass as string)
                me.user = user
                me.pass = pass
            end sub
        end class
    end class

      2、实现处理

    public class configdataclass configdata
        inherits configinformationcollectionbase(of string, myconfiginfo)

        protected overrides sub initialize()sub initialize()
        end sub

        protected overrides readonly property keyname()property keyname() as string
            get
                return "machine"
            end get
        end property

        protected overrides readonly property keynameisfield()property keynameisfield() as boolean
            get
                return false
            end get
        end property

    end class

      测试:

        private sub button3_click()sub button3_click(byval sender as system.object, byval e as system.eventargs) handles button3.click
            dim test as new configdata
            '读文件
            test.read()
            dim item as myconfiginfo

            item = new myconfiginfo
            with item
                .machine = "fk-a01-02"
                .add(new myconfiginfo.login("lzmtw", "001"))
                .add(new myconfiginfo.login("lzm", "002"))
            end with
            test.add(item)

            item = new myconfiginfo
            with item
                .machine = "fk-a01-03"
                .add(new myconfiginfo.login("l", "003"))
                .add(new myconfiginfo.login("lz", "004"))
                .add(new myconfiginfo.login("lzmtw", "001"))
            end with
            test.add(item)
            console.writeline(test.item("fk-a01-03").logins(0).user)
            test.item("fk-a01-03").logins(0).user = "hello"

            test.save() '存盘
            '用另一个打开,看看
            dim test2 as new configdata
            test2.read()
            console.writeline(test2.item("fk-a01-03").logins(0).user)
        end sub

    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表