![](/img/trans.png)
[英]Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#
[英]How do I obtain a list of Collections which contain Objects which Implement an Interface in C# or VB.net
我是.Net编程的新手,想知道Reflection是否适合遍历对象以发现类实例中的Collections。
我正在使用Microsoft.SqlServer.Management.Smo命名空间。
计划是连接到数据库,确定存在哪些集合,然后对于这些集合中的每个集合,如果集合公开实现IScriptable接口的对象,则为该对象生成脚本。
我如何执行以下操作(这是伪代码,因为我正在寻求使用反射或其他方法来执行以下操作的帮助)
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Smo.Agent
Imports Microsoft.SqlServer.Management.Common
Dim db as Database
...
' 1. How do I determine all Collections in the db Object I have created, which implement the IScriptable Interface.
For each myCollection as Collection in db.Database.?Collections?
For each collection_object in myCollection
If collection_object.GetInterface("IScriptable") IsNot Nothing Then
ScriptObjectCreate(collection_object, destFolder & "\" & TypeOf(collection_object).toString() & "\", False)
End If
Next
Next
到目前为止,我可以通过执行以下操作连接到数据库并编写表脚本。
For Each obj As Table In db.Tables
If Not (obj.IsSystemObject) Then
ScriptObjectCreate(obj, destFolder & "\" & "Tables\", False)
End If
Next
我要更改此原因的原因是,不同版本的SQL Server将包含不同的对象集合。 而不是为每种类型编写代码。
For each obj as Table
For each obj as StoredProcedure
For each obj as Trigger
etc...
我想用一个函数枚举db中的所有对象
恐怕这是C#而不是VB.net,但希望您能够解释它?
Server server = new Server();
Database database = server.Databases["ReportServer"];
foreach (PropertyInfo propertyInfo in typeof(Database).GetProperties())
{
if (typeof(SchemaCollectionBase).IsAssignableFrom(propertyInfo.PropertyType))
{
SchemaCollectionBase collection = (SchemaCollectionBase)propertyInfo.GetValue(database, null);
foreach (IScriptable item in collection)
{
PropertyInfo isSystemObjectPropertyInfo = item.GetType().GetProperty("IsSystemObject");
if (isSystemObjectPropertyInfo == null || !(bool)isSystemObjectPropertyInfo.GetValue(item, null))
{
Console.WriteLine("{0} is scriptable and not a system object", item);
// TODO: ScriptObjectCreate(item, destFolder + "\\" + item.GetType() + "\\", false);
}
}
}
}
关键是要使用IsAssignableFrom
来查找集合属性,然后仅提取实现IScripable接口的那些集合中的对象(由于SMO集合不是通用的,因此不可能仅找到那些包含可脚本化对象的集合)。
听起来,您所需要做的就是确定对象是否实现了给定的接口。 如果是这样,那么反思不是正确的工具。 相反,您想使用VB.Net TypeOf
运算符(这是为了进行此测试)。
If TypeOf collection_object is IScriptable Then
完整的例子
For each myCollection as Collection in db.Database.Collections
For each collection_object in myCollection
if TypeOf collection_object is IScriptable Then ..
ScriptObjectCreate(collection_object, destFolder & "\" & TypeOf(collection_object).toString() & "\", False)
End If
Next
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.