开发者

Expression that gets passed a list of items and a way to select a property from one of those items

This is hard to explain, so i will give a usage example, given the code below:

public class ZipCode
{
   ZipCodeId {get;set;}
   Name {get;set;}
}
public class Criteria
{
   List<ZipCode> ZipCodes {get;set;}
}

i want to make a extension method that allows me to write the following

Criteria crit = new Criteria()
crit.SetVal(c => c.ZipCodes, z => z.ZipCodeId, "some value passed in here");

I can make an extension method with a signature like this:

public static void SetVal< T,V,K,Z>(this T crit, Expression< Func< T, V>> selector, Expression< Func< K,Z>> key, string value)

But then i have to call it with

crit.SetVal<PropertySearchCriterionArea, List<ZipCode>, ZipCode, int>(ac => ac.ZipCodes, z => z.ZipCodeId, "开发者_StackOverflow社区some value here");

instead of my wanted version

crit.SetVal(c => c.ZipCodes, z => z.ZipCodeId, "some value passed in here");

As you can see i need to specify every generic parameter type which i do not want to as it should be infered from the signature of the extension method.

So how should i fix this extension method?


If I understand you correctly, a small change in your design should allow a better solution: Change Criteria to the following:

Public Class Criterial<T> { List<T> Values {get; set;} /* add additional properties */ }

And then, the method should look like this:

static void SetVal<T>(this Criteria<T> crit, Expression<Func<Criteria<T>, object>> selector, Expression<Func<T, object>> key, string value)

Which ultimately will allow the following code:

Criteria<ZipCode> c = new Criteria<ZipCode>();
c.SetVal(x => x.Values, y => y.ZipCodeId, "some value passed in here");


Is you mean like it? ↓ 

class Program
{
    static void Main(string[] args)
    {
        Criteria crit = new Criteria();
        crit.SetVal<Criteria, List<ZipCode> , ZipCode , string>(c => c.ZipCodes, z => z.ZipCodeId, "some value passed in here");
    }
}

public class ZipCode
{
   public string ZipCodeId {get;set;}
   public string Name {get;set;}

}

public class Criteria
{
  public List<ZipCode> ZipCodes {get;set;}

}

public static class fordynamic
{
    public static void SetVal<T, V, K, Z>(this T crit, Expression<Func<T, V>> selector, Expression<Func<K, Z>> key, string value)
    { 

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜