Refer to an object being initialized within the initialization?

我是研究僧i 提交于 2021-02-05 12:09:35

问题


I have an object DataParameterInfo (DPI) with a couple of delegate methods that are used to move data from a DataReader into a POCO or to get values out of the POCO.

Example:

new DataParameterInfo<IBulletinPCN>
{
    FieldName = "ChangeProcedure",
    ParameterName = "@ChangeProcedure",
    EntityName = "ChangeProcedure",
    DataType = SqlDbType.NVarChar,
    FieldType = FieldType.Other,
    PopulateEntity = (dr, e) => e.ChangeProcedure = dr.IsDBNull(dr.GetOrdinal("ChangeProcedure")) ? null : dr.GetString(dr.GetOrdinal("ChangeProcedure")),
    ReadEntity = e => e.ChangeProcedure
}

I would like to refer to the Fieldname property of my DPI within the PopulateEntity delegate like such:

    PopulateEntity = (dr, e) => e.ChangeProcedure = dr.IsDBNull(dr.GetOrdinal(FieldName)) ? null : dr.GetString(dr.GetOrdinal(FieldName)),

or maybe

    PopulateEntity = (dr, e) => e.ChangeProcedure = dr.IsDBNull(dr.GetOrdinal(this.FieldName)) ? null : dr.GetString(dr.GetOrdinal(this.FieldName)),

Only the "this" when I try that refers to the class in which the DPI is being created, not the DPI itself.

Can I do what I'm trying, above, and if so, how?


回答1:


You can pass the fieldname to your delegate as a parameter by changing the caller of that delegate:

ex:

PopulateEntity = (dr, e, fieldname) => e.ChangeProcedure = dr.IsDBNull(dr.GetOrdinal(fieldname)) ? null : dr.GetString(dr.GetOrdinal(fieldname))

and in the point where you execute that delegate you say:

PopulateEntity(dr, e, this.fieldname);



回答2:


You cannot refer to another member of a class withtin an object initializer for that class - this would lead to circular references.

You can get around this by simply assigning your PopulateEntity property after the initializer.




回答3:


The var x = new Foo { property = bar } is just a short hand way of doing the old var x = new Foo(); x.property=bar; For this scenario, you'll just have to do it the old fashioned way where there's no problem referencing previously set property values.



来源:https://stackoverflow.com/questions/10449739/refer-to-an-object-being-initialized-within-the-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!