字段去除空格
代码
[AttributeUsage(AttributeTargets.Property,Inherited= false ,AllowMultiple= false )]
public class TrimAttribute:Attribute
{ private readonly Type type;
public TrimAttribute(Type type)
{
this .type = type;
}
public Type Type
{
get { return this .type; }
}
}
public static class TrimAttributeExtension
{
public static void Trim( this Object obj)
{
Type t = obj.GetType();
foreach ( var prop in t.GetProperties())
{
foreach ( var attr in prop.GetCustomAttributes( typeof (TrimAttribute), true ))
{
TrimAttribute tsa = (TrimAttribute)attr;
if (prop.GetValue(obj, null )!= null &&(tsa.Type== typeof ( string )))
{
prop.SetValue(obj,GetPropertyValue(obj,prop.Name).ToString().Trim(), null );
}
}
}
}
private static object GetPropertyValue( object instance, string PropertName)
{
return instance.GetType().InvokeMember(PropertName,System.Reflection.BindingFlags.GetProperty, null ,instance, new Object[]{});
}
}
使用
public class SomeClass
{ [Trim( typeof ( string ))]
string Name { get ; set ; }
}
查询语法
public class SelectClass
{
public void Method1()
{
int [] fool= new int [ 100 ];
for ( int num = 0 ; num < fool.Length; num++)
{
fool[num] = num * num;
}
foreach ( int i in fool)
{
Console.WriteLine(i.ToString());
}
}
public void Method1Select()
{
int [] fool = ( from n in Enumerable.Range( 0 , 100 ) select n * n).ToArray();
fool.ForAll((n) => Console.WriteLine(n));
}
public IEnumerable<Tuple< int , int >> ProduceIndices()
{
for ( int x = 0 ; x < 100 ; x++)
for ( int y = 0 ; y < 100 ; y++)
if (x + y < 100 )
yield return Tuple.Create(x,y);
}
public IEnumerable<Tuple< int , int >> ProduceIndicesSelect()
{
return from x in Enumerable.Range( 0 , 100 )
from y in Enumerable.Range( 0 , 100 )
where x + y < 100
select Tuple.Create(x,y);
}
}
public static class Extensions
{
public static void ForAll<T>( this IEnumerable<T> sequence, Action<T> action)
{
foreach (T item in sequence)
{
action(item);
}
}
}