È questo quello che stai cercando? Penso che si guasta se si passa un tipo di valore non annullabile, ma dovrebbe funzionare quando si utilizzano tipi nullable. Per favore fatemi sapere se c'è qualcosa che ho trascurato.
public static class Extension
{
public static T NullOrPropertyOf<T>(this XAttribute attribute, Func<string, T> converter)
{
if (attribute == null)
{
return default(T);
}
return converter.Invoke(attribute.Value);
}
}
class Program
{
static void Main(string[] args)
{
Func<string, DateTime?> convertDT = (string str) =>
{
DateTime datetime;
if (DateTime.TryParse(str, out datetime))
{
return datetime;
}
return null;
};
Func<string, string> convertStr = (string str) =>
{
return str;
};
XAttribute x = null;
Console.WriteLine(x.NullOrPropertyOf<string>(convertStr));
Console.WriteLine(x.NullOrPropertyOf<DateTime?>(convertDT));
XName t = "testing";
x = new XAttribute(t, "test");
Console.WriteLine(x.NullOrPropertyOf<string>(convertStr));
x = new XAttribute(t, DateTime.Now);
Console.WriteLine(x.NullOrPropertyOf<DateTime?>(convertDT));
}
}
fonte
2010-09-29 15:45:02
E questo: http://stackoverflow.com/questions/336775/pipe-forwards-in-c/337846#337846 –
... e questo: http://stackoverflow.com/questions/854591/how-to-check-for-null-in-a-deep-lambda-expression/854619 # 854619 –
Nota per i progettisti di linguaggio C#: aggiungere qualcosa come un operatore di dereferenziazione null-safe alla lingua è probabile che sia un caratteristica popolare. :-) –