如何使用c#创建一个变量来使用<tsource>来保存类实例?

时间:2016-07-03 17:27:10

标签: c#

我有一个类需要传递一个对象才能创建它的新实例。我的班级看起来像这样

public class TableMapper<TSource>
{
   ........
}

当我创建它的新实例时,我会执行以下操作。

private readonly TableMapper<Client> Mapper; // Client is an instance of a EF model.

现在,我想在新类中创建一个实例作为变量。所以我的新课程将类似于以下内容

// The syntax below is incorrect!!
public class IReportRelation
{
    TableMapper<TSource> localMapper { get; set; } //incorrect usage

    Func<string, string> localProperty { get; set;}

    Func<string, string> foreignProperty { get; set; }

    TableMapper<TSource> foreignMapper { get; set; } //incorrect usage
}

然而,从另一个名为TableMapper的类中,我需要一个方法,在类似的方法中创建IReportRelation类的实例

public IReportRelation Relation<TProperty>(Expression<Func<TSource, TProperty>> lProperty, TableMapper<TSource> fMapper, Expression<Func<TSource, TProperty>> fKey)
{
    return new IReportRelation { localProperty = lProperty; foreignMapper = fMapper; foreignProperty = fKey};

}

我希望我可以用类似的方式调用我的Relation方法

public override List<IReportRelation> ReportRelations
        {
            get
            {
                new List<IReportRelation>
                {
                    Mapper.Relation(x => x.ClientId, TableMapper<Client>, c => c.Id),
                };
            }
        }

我怎样才能正确创建具有包含另一个类的实例的属性的地方?我将传递给它的是什么?

1 个答案:

答案 0 :(得分:2)

IReportRelation - 接口更改为以下内容:

public class IReportRelation<TLocal, TForeign>
{
    public TableMapper<TLocal> localMapper { get; set; }

    public Func<string, string> localProperty { get; set; }

    public Func<string, string> foreignProperty { get; set; }

    public TableMapper<TForeign> foreignMapper { get; set; }
}

使用两个不同的通用参数,您可以在源和目标

之间有所不同

编辑:

public IReportRelation<T1, T2> Relation<T1, T2>(TableMapper<T1> lMapper, Func<string, string> lProperty, TableMapper<T2> fMapper, Func<string, string> fKey)
    {
        return new IReportRelation<T1, T2> { localMapper = lMapper, localProperty = lProperty, foreignMapper = fMapper, foreignProperty = fKey };
    }

我强烈推荐你,不要在课程前加上IReportRelation表示,它是一个接口

<强>用法

public void SomeMethod(){                
            var xx = this.Relation(new TableMapper<Student>(), dummy, new TableMapper<Department>(), dummy);
        }

        string dummy(string xx)
        {
            return xx + "Hello";
        }