C# 零碎
1.一个集合转换为另外个集合?
linq 的select 映射,还可以结合匿名类型生成匿名类型的集合绑定到列表控件。
var datasource = RencentRecipes.Select(r => new { Name = r.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)[2], FullPath = r }).ToList(); this.rencent_list.DataSource = datasource; this.rencent_list.DisplayMember = "Name";
this.rencent_list.SelectedIndex = -1;
2. 从控件列表选择选项后反射获取匿名类型的属性值。
var selectedRecentItem = this.rencent_list.SelectedItem; var recipeName = selectedRecentItem.GetType().GetProperty("Name").GetValue(selectedRecentItem).ToString(); var selectedRecentItemPath = selectedRecentItem.GetType().GetProperty("FullPath").GetValue(selectedRecentItem).ToString();
3. 反射能获取动态类型的值,但是设置动态类型的值的时候出错,应该是没有SetMethod,只读的。


你不给我属性,那么你的字段我总可以修改吧,下面是解决方案。
public static class AnonymousObjectMutator { private const BindingFlags FieldFlags = BindingFlags.NonPublic | BindingFlags.Instance; private static readonly string[] BackingFieldFormats = { "<{0}>i__Field", "<{0}>" }; public static T Set<T, TProperty>( this T instance, Expression<Func<T, TProperty>> propExpression, TProperty newValue) where T : class { var pi = (propExpression.Body as MemberExpression).Member; var backingFieldNames = BackingFieldFormats.Select(x => string.Format(x, pi.Name)).ToList(); var fi = typeof(T) .GetFields(FieldFlags) .FirstOrDefault(f => backingFieldNames.Contains(f.Name)); if (fi == null) throw new NotSupportedException(string.Format("Cannot find backing field for {0}", pi.Name)); fi.SetValue(instance, newValue); return instance; } }
验证通过
var person = new { Name = "Ghx", Age = 18 }; //var propertyInfo = person.GetType().GetProperty("Name"); //propertyInfo.SetValue(person, "whenming"); var name = person.GetType().GetProperty("Name").GetValue(person).ToString(); person.Set(x => x.Name, "Tim"); var nameModified = person.Name;
4. C# 关键字 is out 等省了定义临时变量的操作
if (int.TryParse("12", out int ff) && ff > 0) Console.WriteLine(ff); if (node.Tag is RecipeItem recipe) { return recipe.ValidationMessag; }
5. 枚举值可以Foreach 和加对应的Int 值做为前进后退的步进
for (HardwareType hardwareType = HardwareType.START + 1; hardwareType < HardwareType.END; hardwareType++) { //to do }
private enum MarkingStep { BeforeFirstMarking = 0, FirstMarked = 1, //第一次Marking后图上只有一个十字标 BeforeSecondMarking = 2, //尝试点选第二个十字标但未Marking SecondMarked = 3 } this.CurrentMarkStep += 1; //前进一个步骤 this.CurrentMarkStep = this.CurrentMarkStep - 1; //后退一个步骤

浙公网安备 33010602011771号