如何将项目类型转换为共享类库类型

时间:2015-07-22 22:12:49

标签: c# .net vb.net mapping

(C#代码示例位于问题的底部。)

我有一个在多个解决方案之间共享的类库,其类型为SharedType。我在类库中有一个方法来处理这种类型的集合:

Sub ProcessSharedTypeEnumerable(src As IEnumerable(Of SharedType))
    'do something here
End Sub

每个解决方案都有自己的特定类型,应该映射/转换为SharedType

Namespace Project1
    Class ProjectType
    End Class
End Namespace

如何调用ProcessSharedTypeEnumerable而无需在呼叫网站将ProjectType转换为SharedType

Dim lst As New List(Of ProjectType)
'populate list

'instead of this:
ProcessSharedTypeEnumerable(lst.Select(Function(x) New SharedType With { 'populate members here' })
'use this:
ProcessSharedTypeEnumerable(lst)

我知道我可以让项目类型实现类库中的接口,该类具有映射到共享类型的方法

Public Interface ISharedTypeMappable
    Function ToSharedType() As SharedType
End Interface

然后ProcessSharedTypeEnumerable方法可以IEnumerable(Of ISharedTypeMappable),我可以在.Select(Function(x) x.ToSharedType)内拨打ProcessSharedTypeEnumerable来获取IEnumerable(Of SharedType)

有更“正确”的方法吗?通用协方差和隐式转换?一些.NET内置的转换机制?

C#代码示例

类库方法:

static class Utils { //I know it's an awful name ...
    static void ProcessSharedTypeEnumerable(IEnumerable<SharedType> src) {
        //do something here
    }
}

项目代码:

var lst = new List<ProjectType>();
//populate list

//instead of this:
Utils.ProcessSharedTypeEnumerable(lst.Select(x=>new SharedType { /* populate properties here */}));
//do this
Utils.ProcessSharedTypeEnumerable(lst);

更新

我不希望ProjectType继承SharedType有两个原因(1)ProjectType已经从不同的基本类型继承,(2)SharedType可能有成员不应该在ProjectType

2 个答案:

答案 0 :(得分:0)

继承?

Sub Main()
    Dim lst As New List(Of ProjectType) From {
        New ProjectType With {.s = "1"},
        New ProjectType With {.s = "2"},
        New ProjectType With {.s = "3"}
    }
    SharedType.ProcessSharedTypeEnumerable(lst)
End Sub

Shared Sub ProcessSharedTypeEnumerable(src As IEnumerable(Of SharedType))
    For Each st As SharedType In src
        MsgBox(st.s)
    Next
End Sub

Class SharedType
    Property s As String
End Class

Class ProjectType
    Inherits SharedType
End Class

答案 1 :(得分:0)

编辑:现在这是一个社区维基回答

根据要求,我尝试实施Operator Widening CType。但它不起作用。也许读这篇文章的人可以解决这个问题。

Module Module1

  Sub Main()
    Dim lst As New List(Of ProjectType) From {
        New ProjectType With {.t = "1"},
        New ProjectType With {.t = "2"},
        New ProjectType With {.t = "3"}
    }
    MsgBox(CType(lst(0), SharedType).s) 'This works'
    ProcessSharedTypeEnumerable(lst) 'This does not :-( '
    ProcessSharedTypeEnumerable(lst.Cast(Of SharedType).ToList) 'Neither does this :-( '
  End Sub

  Sub ProcessSharedTypeEnumerable(src As IEnumerable(Of SharedType))
    For Each st As SharedType In src
      MsgBox(st.s)
    Next st
  End Sub

  Class SharedType
    Property s As String
  End Class

  Class ProjectType
    Property t As String

    Public Shared Widening Operator CType(p As ProjectType) As SharedType
      Return New SharedType With {.s = p.t}
    End Operator
  End Class
End Module