C#将B类中的对象分配给A类

时间:2017-03-06 10:01:49

标签: c#

我有两个课程。

A类:

public class A {
    prop string p1  { get; set; }
    prop string p2  { get; set; }
    prop string p3  { get; set; }
}

B类:

public class B {
    prop string p1  { get; set; }
    prop string p3  { get; set; }
}

现在假设我们有一个来自类B的对象,我们希望将它分配给类A中的对象。

B b_obj = new B(){
     p1 = "something",
     p2 = "something else"
} 

A a_obj = new A(){
    p1 = b_obj.p1,
    p3 = b_obj.p3,
}

我认为上述解决方案不是最佳方式。

最佳做法b_obj分配给班级A中的其他对象是什么?

  

提示:class B中的所有媒体资源在class A

中都有类似的属性

4 个答案:

答案 0 :(得分:3)

您始终可以实现隐式或显式强制转换运算符:

public class B
{
     public static explicit operator A(B b)
     {
          return new A() {
                           p1 = b_obj.p1,
                           p3 = b_obj.p3,
                         }
     }

     //...
 }

现在,您只需在A B var a = (A)b; A时编写即可。

B

如果您无法访问public static A ToA(this B b) { return ... } var a = b.ToA(); ,则可以实施扩展方法:

java.lang.IllegalStateException: Can't find method acknowledge with 0 parameters in com.vaadin.shared.ui.ui.UIServerRpc
        at com.vaadin.server.ServerRpcMethodInvocation.findInvocationMethod(ServerRpcMethodInvocation.java:84) ~[vaadin-server-7.7.7.jar:?]
        at com.vaadin.server.ServerRpcMethodInvocation.<init>(ServerRpcMethodInvocation.java:42) ~[vaadin-server-7.7.7.jar:?]
        at com.vaadin.server.communication.ServerRpcHandler.parseServerRpcInvocation(ServerRpcHandler.java:590) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.ServerRpcHandler.parseInvocation(ServerRpcHandler.java:534) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.ServerRpcHandler.parseInvocations(ServerRpcHandler.java:500) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:336) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:273) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.PushHandler$2.run(PushHandler.java:148) ~[vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.PushHandler.callWithUi(PushHandler.java:240) [vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.PushHandler.onMessage(PushHandler.java:494) [vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.PushAtmosphereHandler.onMessage(PushAtmosphereHandler.java:87) [vaadin-server-7.7.7.jar:7.7.7]
        at com.vaadin.server.communication.PushAtmosphereHandler.onRequest(PushAtmosphereHandler.java:77) [vaadin-server-7.7.7.jar:7.7.7]
        at org.atmosphere.cpr.AsynchronousProcessor.action(AsynchronousProcessor.java:199) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.cpr.AsynchronousProcessor.suspended(AsynchronousProcessor.java:107) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.container.Servlet30CometSupport.service(Servlet30CometSupport.java:66) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.cpr.AtmosphereFramework.doCometSupport(AtmosphereFramework.java:2075) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.websocket.DefaultWebSocketProcessor.dispatch(DefaultWebSocketProcessor.java:571) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.websocket.DefaultWebSocketProcessor$3.run(DefaultWebSocketProcessor.java:333) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.util.VoidExecutorService.execute(VoidExecutorService.java:101) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.websocket.DefaultWebSocketProcessor.dispatch(DefaultWebSocketProcessor.java:328) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.websocket.DefaultWebSocketProcessor.invokeWebSocketProtocol(DefaultWebSocketProcessor.java:425) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.container.JSR356Endpoint$1.onMessage(JSR356Endpoint.java:214) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.atmosphere.container.JSR356Endpoint$1.onMessage(JSR356Endpoint.java:211) [atmosphere-runtime-2.2.9.vaadin2.jar:2.2.9.vaadin2]
        at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:393) [tomcat-websocket.jar:8.0.24]
        at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:494) [tomcat-websocket.jar:8.0.24]
        at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:289) [tomcat-websocket.jar:8.0.24]
        at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:130) [tomcat-websocket.jar:8.0.24]
        at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:60) [tomcat-websocket.jar:8.0.24]
        at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:203) [tomcat-websocket.jar:8.0.24]
        at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:198) [tomcat-coyote.jar:8.0.24]
        at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:96) [tomcat-coyote.jar:8.0.24]
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:663) [tomcat-coyote.jar:8.0.24]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527) [tomcat-coyote.jar:8.0.24]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484) [tomcat-coyote.jar:8.0.24]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_66]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_66]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.24]
        at java.lang.Thread.run(Thread.java:745) [?:1.8.0_66]

使用方法类似:

@NoLoadingIndicator
public void acknowledge();

答案 1 :(得分:2)

您可以使用automapper http://automapper.org/ 然后你可以像这样使用它:

AutoMapper.Mapper.CreateMap<A, B>();
var a = ...
var model = AutoMapper.Mapper.Map<B>(a);

答案 2 :(得分:1)

您可以使用AutoMapper(请参阅denisv的回答),它根据名称提供类之间的映射。然后,您可以根据需要自定义映射。

您还可以编写一些扩展方法:

Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions

Public Class Form1
    Public Property gridResults As Object

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        OpenFileDialog2.Title = "Velg fil ..."


        OpenFileDialog2.InitialDirectory = "C:users\<currentuser>\Documents"
        OpenFileDialog2.Filter = "Alle filer|*.*|Excel 2003|*.xls|Excel|*.xlsx"
        OpenFileDialog2.FilterIndex = 2

        OpenFileDialog2.ShowDialog()


    End Sub


    Private Sub OpenFileDialog2_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog2.FileOk


        Dim strm As System.IO.Stream
        strm = OpenFileDialog2.OpenFile()

        TextBox2.Text = OpenFileDialog2.FileName.ToString()

        If Not (strm Is Nothing) Then
            strm.Close()
        End If

        Me.Button5_Click(sender, e)

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

        If String.IsNullOrEmpty(TextBox2.Text) Then
            MessageBox.Show("Klikk ""Bla gjennom"" for å velge en fil", "Ingen inndatafil")
            Exit Sub
        End If

        Dim FilePath As String = OpenFileDialog2.FileName

        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim DtSet As System.Data.DataSet
        Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
        MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & ";Extended Properties=Excel 8.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
        MyCommand.TableMappings.Add("Table", "Net-informations.com")
        DtSet = New System.Data.DataSet
        MyCommand.Fill(DtSet)
        DataGridView2.DataSource = DtSet.Tables(0)
        MyConnection.Close()

    End Sub

    Public Function GetElementColorsValues(elementName As String) As Decimal()
        Dim ULArray(4) As Decimal
        Select Case elementName
            Case "As (Arsen)"
                ULArray(0) = 8
                ULArray(1) = 20
                ULArray(2) = 50
                ULArray(3) = 600
                ULArray(4) = 1000
            Case "Cd (Kadmium)"
                ULArray(0) = 1.5
                ULArray(1) = 10
                ULArray(2) = 15
                ULArray(3) = 30
                ULArray(4) = 1000
            Case "Cu (Kopper)"
                ULArray(0) = 100
                ULArray(1) = 200
                ULArray(2) = 1000
                ULArray(3) = 8500
                ULArray(4) = 25000
            Case "Cr (Krom)"
                ULArray(0) = 50
                ULArray(1) = 200
                ULArray(2) = 500
                ULArray(3) = 2800
                ULArray(4) = 25000
            Case "Hg (Kvikksølv)"
                ULArray(0) = 1
                ULArray(1) = 2
                ULArray(2) = 4
                ULArray(3) = 10
                ULArray(4) = 1000
            Case "Ni (Nikkel)"
                ULArray(0) = 60
                ULArray(1) = 135
                ULArray(2) = 200
                ULArray(3) = 1200
                ULArray(4) = 2500
            Case "Pb (Bly)"
                ULArray(0) = 60
                ULArray(1) = 100
                ULArray(2) = 300
                ULArray(3) = 700
                ULArray(4) = 2500
            Case "Zn (Sink)"
                ULArray(0) = 200
                ULArray(1) = 500
                ULArray(2) = 1000
                ULArray(3) = 5000
                ULArray(4) = 25000
        End Select
        Return ULArray
    End Function

    'Fargeleggingsrutine - gir feilmelding
    Private Sub SetDGVColColor()

        Dim ULArray As Decimal()
        Dim curValue As String
        Dim decimalValue As Decimal
        Dim colName = ""
        For col As Integer = 2 To DataGridView2.ColumnCount - 1
            colName = DataGridView2.Columns(col).Name
            ULArray = GetElementColorsValues(colName)
            For Each row As DataGridViewRow In DataGridView2.Rows
                If (Not row.IsNewRow) Then
                    curValue = row.Cells(colName).Value
                    If (curValue IsNot Nothing) Then
                        Decimal.TryParse(curValue, decimalValue)
                        ' the above TryParse line will set decimalValue to 0 if curValue is not a valid decimal i.e `<0.005`
                        Select Case decimalValue
                            Case >= ULArray(4)
                                row.Cells(colName).Style.BackColor = Color.BlueViolet
                            Case >= ULArray(3)
                                row.Cells(colName).Style.BackColor = Color.Red
                            Case >= ULArray(2)
                                row.Cells(colName).Style.BackColor = Color.Orange
                            Case >= ULArray(1)
                                row.Cells(colName).Style.BackColor = Color.Yellow
                            Case >= ULArray(0)
                                row.Cells(colName).Style.BackColor = Color.LawnGreen
                            Case Else
                                row.Cells(colName).Style.BackColor = Color.DodgerBlue
                        End Select
                    End If ' ignore empty cell
                End If ' ignore the new row
            Next
        Next

    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        SetDGVColColor()
    End Sub

    'Første svar fra JohnG
    'Fjerde forsøk på eksport
    Private Sub ExportToExcel()
        Dim excel As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
        Dim workbook As Microsoft.Office.Interop.Excel._Workbook = excel.Workbooks.Add(Type.Missing)
        Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
        excel.Visible = True
        Try
            worksheet = workbook.ActiveSheet
            worksheet.Name = "ExportedFromDataGrid"
            Dim cellRowIndex As Integer = 1
            Dim cellColumnIndex As Integer = 1
            'gets header rows.
            For Each column In DataGridView2.Columns
                worksheet.Cells(1, column.Index + 1).Value = column.Name
            Next
            'gets all other rows
            Dim rowIndex = 2
            For Each row As DataGridViewRow In DataGridView2.Rows
                If Not row.IsNewRow Then
                    For colIndex As Integer = 0 To DataGridView2.Columns.Count - 1
                        worksheet.Cells(rowIndex, colIndex + 1).Value = row.Cells(colIndex).Value.ToString
                    Next
                End If
                rowIndex += 1
            Next

            ' Substituted code below that loops through each column with data
            ' then sets the color for each of those columns by calling the SetColColor method
            For index As Integer = 2 To DataGridView2.Columns.Count
                Dim colName = DataGridView2.Columns(index).Name
                SetExcelColColor(worksheet, colName, index + 1)
            Next
            MessageBox.Show("Closing excel: save if needed!")
            'workbook.SaveAs("YourFileName..",)
            workbook.Close()
            excel.Quit()
            Marshal.ReleaseComObject(worksheet)
            Marshal.ReleaseComObject(workbook)
            Marshal.ReleaseComObject(excel)
        Catch
            MessageBox.Show("Error")
        End Try
    End Sub

    'andre eksportrutine med fargelegging fra JohnG
    Private Sub SetExcelColColor(worksheet As Microsoft.Office.Interop.Excel._Worksheet, colName As String, colIndex As Integer)
        Dim rIndex = 2
        Dim cIndex = colIndex
        Dim ULArray = GetElementColorsValues(colName)
        Dim curValue As String
        Dim decimalValue As Decimal

        For Each row As DataGridViewRow In DataGridView2.Rows
            If (Not row.IsNewRow) Then
                curValue = row.Cells(colName).Value
                If (curValue IsNot Nothing) Then
                    Decimal.TryParse(curValue, decimalValue)
                    Select Case decimalValue
                        Case >= ULArray(4)
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.BlueViolet)
                        Case >= ULArray(3)
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
                        Case >= ULArray(2)
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange)
                        Case >= ULArray(1)
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow)
                        Case >= ULArray(0)
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LawnGreen)
                        Case Else
                            worksheet.Cells(rIndex, cIndex).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DodgerBlue)
                    End Select
                    rIndex += 1
                End If ' ignore empty cell 
            End If ' ignore new row
        Next
    End Sub


    Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
        Me.ExportToExcel()
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        System.Windows.Forms.Application.Exit()
    End Sub


End Class

答案 3 :(得分:-1)

首先初始化B类并设置值。然后创建这样一个类:

mysql> kill put_process_id_here;

}

并将A和B类作为参数

传递给此类