Dear everyone,
This morning I received the email from Microsoft that they just created for me the blog at http://weblogs.asp.net. I really happy about that and decided to moving my house from Blogger (http://thangcq.blogspot.com) to asp.net blogs (http://weblogs.asp.net/thangchung). If anyone want to read some articles at Blogger, you still read all of it at those. I will not move all articles to asp.net weblogs, and in the future I will try to write new articles at asp.net blog. I hope anyone will support me in that. And in next time, I will try to finish the NMA project at codeplex.
Sorry for this inconvenience!
Wednesday, June 16, 2010
Thursday, June 10, 2010
Cast anonymous types
Today, when coding for one module in my project at company, I had a problem that make me crazy. Used var keyword on .NET 3.5, it's a anonymous type, so when we go out its scope, we don't know its type. I think many people also had this problem like me. So after using many methods for solve this problem, I also found the best solution for it. Thanks Alex for best idea from him! Now there are some my effort for solve it:
+ First thing, I tried to coding and gave this error:
Cannot cast 'exampleObj' (which has an actual type of '<>f__AnonymousType0<string,string>') ...
+ Next, I started my working for solving it. Wrote the extension method for cast anonymous method:
http://blogs.msdn.com/b/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx?wa=wsignin1.0
http://msdn.microsoft.com/en-us/library/bb383973.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
+ First thing, I tried to coding and gave this error:
Cannot cast 'exampleObj' (which has an actual type of '<>f__AnonymousType0<string,string>
+ Next, I started my working for solving it. Wrote the extension method for cast anonymous method:
public static class Extender
{
public static T Cast(this object obj, T what)
{
return (T)obj;
}
}
+ Object that content the anonymous type:var exampleObj = from node in rootNode.Descendants()
where node.FirstAttribute != null && node.FirstAttribute.Value == "ExampleName"
select new
{
FirstField = node.FirstAttribute.Value,
SecondField = node.LastAttribute.Value
};
Binding this object to ListView:exampleObj .All(x =>
{
lstView.Items.Add(x);
lstView.ValueMember = "FirstField ";
lstView.DisplayMember = "SecondField ";
return true;
});
+ And used the extension method for cast anonymous type:var exampleObj= lstView.SelectedItem;
var castObj = exampleObj.Cast(new {
FirstField = "", SecondField = ""
});
Now we can use it very normally:var firstField = castObj.FirstField; var secondField = castObj.SecondField;+ References:
http://blogs.msdn.com/b/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx?wa=wsignin1.0
http://msdn.microsoft.com/en-us/library/bb383973.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
Subscribe to:
Posts (Atom)
