Return-Type in Base&继承类 [英] Return-Type in Base & Inherited Class

查看:69
本文介绍了Return-Type in Base&继承类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


我有一个BaseClass和许多类,它们都直接从BaseClass继承。


BaseClass中的一个函数是(de)将(继承的)类序列化到磁盘或从磁盘序列化。


1.反序列化如下:


#Region"加载


公共函数加载(ByVal path As String)作为对象


返回DeserializeXML(className,path)


结束函数


公共函数加载(ByVal路径为字符串,ByVal用户为字符串)作为对象


返回DeserializeXML(className,path,user)


结束函数


#End Region


"问题"使用这种方法是当一个类得到'实例化时,它将作为一个Object而不是一个派生类型返回,所以我必须将其转换为(严格选项):


Dim Setup作为New Namespace.Settings.Setup


Setup = DirectCast(Setup.Load(PathInfo.Settings),Namespace.Settings.Setup)


如果我可以使用正确的Type返回它,代码将减少为:


Dim Setup As New Namespace.Settings.Setup


设置= Setup.Load(PathInfo.Settings)


一种方法是将Load-Method放在每个派生类中(但这不是非常OO),所以我想Dynamicaly(genericaly)更改Load-Method的Return-Type。


只有:我还没有得到如何做到的线索!


2.反序列化如下:


#Region"坚持


Public Sub Persist(ByVal path As String)


试试


SerializeXML (我,className,路径)


Catch ex As Exception


MsgBox(ex.ToString)


结束尝试


结束子


Public Sub Persist(ByVal path As String,ByVal user as String)


尝试


SerializeXML(我,className,路径,用户)


Catch ex As Exception


MsgBox(ex.ToString)


结束尝试


结束子


#End Region


以下代码在一个模块中(在同一个项目中)


Private Sub PerformSerialization(ByVal o As Object,ByVal callerClass As String,ByVal path As String,ByVal user As String)


.........


.........

Dim swFile作为StreamWriter =新IO.StreamWriter(fileName)


Dim t As Type


D. im pi As PropertyInfo()


Dim p As PropertyInfo


选择Case callerClass。


Case" settings.setup"


t = GetType(设置)


.. .......


.........


Case" settings.mailserver"


t = GetType(MailServer)


.........


... ......


案例" settings.products"


t = GetType(产品)


结束选择


pi = t.GetProperties()


''加密字符串


For Each p In pi


如果p.PropertyType.ToString =" System.String"然后我也认为这种语法是Not Done。什么是最好的语法?


p.SetValue(o,Crypto.EncryptString(p.GetValue(o,Nothing)),没什么)


结束如果


下一页


''保存到磁盘

xmlSerializer =新Xml.Serialization.XmlSerializer(t)

xmlSerializer.Serialize(swFile,o)


swFile.Close()


结束子


不是很喔!


而不是传递一个对象我想传递继承类的类型。但我怎么知道在BaseClass中。


任何线索都会非常感激。


Michael


PS:我使用vs.Net 2003

Hello,

I have a BaseClass and many Classes which all inherit (directly) from the BaseClass.

One of the functions in the BaseClass is to (de)serialize the (inherited) Class to/from disk.

1. The Deserialization goes like:

#Region " Load "

Public Function Load(ByVal path As String) As Object

Return DeserializeXML(className, path)

End Function

Public Function Load(ByVal path As String, ByVal user As String) As Object

Return DeserializeXML(className, path, user)

End Function

#End Region

The "problem" with this approach is that when a class get''s instanciated it is returned as an Object instead a the Derived type so I have to Cast it (option strict on):

Dim Setup As New Namespace.Settings.Setup

Setup = DirectCast(Setup.Load(PathInfo.Settings), Namespace.Settings.Setup)

If I could return it with the right Type the code would be reduced to:

Dim Setup As New Namespace.Settings.Setup

Setup = Setup.Load(PathInfo.Settings)

One way to do this is to put the Load-Method in each derived Class (but that wouldn''t be very OO), so I''d like to Dynamicaly (genericaly) Change the Return-Type of the Load-Method.

Only: I haven''t got a clue how-to!

2. The Deserialization goes like:

#Region " Persist "

Public Sub Persist(ByVal path As String)

Try

SerializeXML(Me, className, path)

Catch ex As Exception

MsgBox(ex.ToString)

End Try

End Sub

Public Sub Persist(ByVal path As String, ByVal user As String)

Try

SerializeXML(Me, className, path, user)

Catch ex As Exception

MsgBox(ex.ToString)

End Try

End Sub

#End Region

The following code is in a Module (in the same project)

Private Sub PerformSerialization(ByVal o As Object, ByVal callerClass As String, ByVal path As String, ByVal user As String)

.........

.........

Dim swFile As StreamWriter = New IO.StreamWriter(fileName)

Dim t As Type

Dim pi As PropertyInfo()

Dim p As PropertyInfo

Select Case callerClass.

Case "settings.setup"

t = GetType(Setup)

.........

.........

Case "settings.mailserver"

t = GetType(MailServer)

.........

.........

Case "settings.products"

t = GetType(Products)

End Select

pi = t.GetProperties()

'' Encrypt Strings

For Each p In pi

If p.PropertyType.ToString = "System.String" Then I also think this syntax is "Not Done". What would be the Best Syntax?

p.SetValue(o, Crypto.EncryptString(p.GetValue(o, Nothing)), Nothing)

End If

Next

'' Save to Disk

xmlSerializer = New Xml.Serialization.XmlSerializer(t)

xmlSerializer.Serialize(swFile, o)

swFile.Close()

End Sub

Not very OO hum!

Instead of passing "an Object" I would like to pass the Type of the Inheriting Class. But how do I "know" that in the BaseClass.

Any clues would be greatly appreciated.

Michael

PS: I use vs.Net 2003

推荐答案

嗨迈克尔,


1.我认为我们无法传递ctype函数的字符串类型。但是我想b $ b你认为你可以看看下面的代码,这对你有用吗?


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs)处理Button1.Click

Dim kc As Color = Color.FromKnownColor(KnownColor.Blue)

Dim cr As Color = Color.FromArgb(kc.ToArgb())

Dim c As KnownColor

For i As Integer = 1 to 137

If Color.FromKnownColor(i)。ToArgb()= cr.ToArgb()然后

Debug.WriteLine(CType(i,KnownColor).ToString())

结束If

下一页

Dim o As new derivedclass

o.str =" Test"

o.se( )

Dim b作为derivedclass

b = o.de()

MsgBox(b.str)

结束Sub


公共类基类

Public Sub se()

Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType ())

Dim writer As TextWriter = New StreamWriter(" Test.xml")

ser.Se rialize(作家,我)

writer.Close()

End Sub


Public Function de()As Object

Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType())

Dim fs As New FileStream(" Test.xml",FileMode.Open)

返回ser.Deserialize(fs)

结束功能

结束班级

公共类派生类

继承baseclass

Public str As String

End Class


2.

PropertyInfo.PropertyType属性[Visual Basic]

获取此属性的类型。

PropertyType是readonly属性
http://msdn.microsoft.com/library/de...us/ cpref / html /

frlrfSystemReflectionPropertyInfoClassPropertyType Topic.asp

3.

即使方法在基类中。

例如

Public Functi on Hello(ByVal o As BaseClass)As String

返回o.GetType()。ToString()

结束函数

但是如果我们通过派生类的实例进入方法,我们仍然会得到

派生方法的类型。


祝你好运,

Peter Huang

Microsoft在线合作伙伴支持


安全! - www.microsoft.com/security

此帖子原样是按原样提供的。没有保证,也没有授予任何权利。

Hi Michael,

1. I think we can not pass the ctype function the type of string. But I
think you may take a look at the code below, did that work for you?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim kc As Color = Color.FromKnownColor(KnownColor.Blue)
Dim cr As Color = Color.FromArgb(kc.ToArgb())
Dim c As KnownColor
For i As Integer = 1 To 137
If Color.FromKnownColor(i).ToArgb() = cr.ToArgb() Then
Debug.WriteLine(CType(i, KnownColor).ToString())
End If
Next
Dim o As New derivedclass
o.str = "Test"
o.se()
Dim b As derivedclass
b = o.de()
MsgBox(b.str)
End Sub

Public Class baseclass
Public Sub se()
Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType())
Dim writer As TextWriter = New StreamWriter("Test.xml")
ser.Serialize(writer, Me)
writer.Close()
End Sub

Public Function de() As Object
Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType())
Dim fs As New FileStream("Test.xml", FileMode.Open)
Return ser.Deserialize(fs)
End Function
End Class
Public Class derivedclass
Inherits baseclass
Public str As String
End Class

2.
PropertyInfo.PropertyType Property [Visual Basic]
Gets the type of this property.
PropertyType is readonly property
http://msdn.microsoft.com/library/de...us/cpref/html/
frlrfSystemReflectionPropertyInfoClassPropertyType Topic.asp

3.
Even if the method is in the baseclass.
e.g.
Public Function Hello(ByVal o As BaseClass) As String
Return o.GetType().ToString()
End Function
but if we pass an derived class instance into the method, we will still get
the derived method''s type.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.


嗨彼得,


感谢您的回复。 />

我偶然发现了另一个问题:


我有一个LibraryClassAssembly_Phone

Assembly_Phone有< ;汇编:AssemblyDefaultAlias(我不知道。)>

让我们假设它包含一个方法:


Class Hello

Sub WhoIsCallingMe()

Dim at As Type = GetType(AssemblyDefaultAliasAttribute)

Dim r()As Object =

Me.GetType.Assembly.GetCallingAssembly.GetCustomAt tributes(at,False)

如果IsNothing(r)或r.Length = 0则

MsgBox(No Default defined ;)

Else

MsgBox(CType(r(0),AssemblyDefaultAliasAttribute).DefaultAlias)

结束如果

结束子

结束类


我在另一个解决方案Assembly_EX中有另一个程序集(可执行文件) E"


Assembly_EXE引用Assembly_Phone

Assembly_EXE有< Assembly:AssemblyDefaultAlias(" It's me!)>


Sub Main()

Dim Ring As New Assembly_Phone.Hello

Ring.WhoIsCallingMe()

结束< br $>
结束Sub


运行Assembly_EXE应该显示一个Messagbox提示:它就是我!但是b $ b'它提示我不知道。


我在这里缺少什么?


问候,


Michael
Hi Peter,

Thanks for your reply.

I have though stumbled upon another Issue namely:

I have a LibraryClass "Assembly_Phone"
Assembly_Phone has <Assembly: AssemblyDefaultAlias("I don''t know.")>
Lets suppose it contains a Method:

Class Hello
Sub WhoIsCallingMe()
Dim at As Type = GetType(AssemblyDefaultAliasAttribute)
Dim r() As Object =
Me.GetType.Assembly.GetCallingAssembly.GetCustomAt tributes(at, False)
If IsNothing(r) Or r.Length = 0 Then
MsgBox("No Default defined")
Else
MsgBox(CType(r(0), AssemblyDefaultAliasAttribute).DefaultAlias)
End If
End Sub
End Class

I have another Assembly (Executable) in antoher Solution "Assembly_EXE"

Assembly_EXE references Assembly_Phone
Assembly_EXE has <Assembly: AssemblyDefaultAlias("It''s me!")>

Sub Main()
Dim Ring As New Assembly_Phone.Hello
Ring.WhoIsCallingMe()
End
End Sub

Running Assembly_EXE should display a Messagbox prompting: "It''s me!" BUT
it''s prompting "I don''t know".

What am I missing here?

Regards,

Michael


嗨Michael,


It奇怪的是我无法重现你的代码问题。

但我想你可能会尝试在WhoIsCallingMe方法中添加一个调试输出

来看看我是什么。 GetType.Assembly.GetCallingAssembly实际上是。

根据我的测试,这将返回调用dll的exe文件。

Dim at As Type = GetType(AssemblyDefaultAliasAttribute)

Debug.WriteLine(Me.GetType.Assembly.GetCallingAsse mbly.FullName)

Dim r()As Object =

Me.GetType.Assembly .GetCallingAssembly.GetCustomAttbute(at,False)


您可以尝试一下,让我知道结果。


祝你好运,


Peter Huang

Microsoft在线合作伙伴支持


安全! - www.microsoft.com/security

此帖子原样是按原样提供的。没有保证,也没有授予任何权利。

Hi Michael,

It is strange that I can not reproduce problem with your code.
But I think you may try to add a debug output in the WhoIsCallingMe method
to see what is the Me.GetType.Assembly.GetCallingAssembly actually is.
Based on my test, this will return the exe file which call the dll.
Dim at As Type = GetType(AssemblyDefaultAliasAttribute)
Debug.WriteLine(Me.GetType.Assembly.GetCallingAsse mbly.FullName)
Dim r() As Object =
Me.GetType.Assembly.GetCallingAssembly.GetCustomAt tributes(at, False)

You may have a try and let me know the result.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.


这篇关于Return-Type in Base&amp;继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆