c#技巧

来源:互联网 发布:腾讯q币充值软件 编辑:程序博客网 时间:2024/05/21 21:03

1、obj转为string        

/// <summary>

        /// 对象obj转换为typeid
        /// </summary>
        /// <param name="info"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);

        }

obj转化任意类型      使用is/as示例

is转换规则:

1. 检查对象类型的兼容性,并返回结果true(false);
2.不会抛出异常;
3.如果对象为null,刚返回false;

示例:

    object o = "abc";
    if (o is string) //执行第一次类型兼容性检查
    {
        string s = (string)o; //执行第二次类型兼容性检查,并转换
        MessageBox.Show("转换成功!");
    }
    else
    {
        MessageBox.Show("转换失败!");
    }

as转换规则:

1.检查对象类型的兼容性,并返回转换结果,如果不兼容则返回null;
2.不会抛出异常;
3.如果结果判断为空,则强制执行类型转换将抛出NullReferenceException异常;

示例:

    object o = "abc";
    string s = o as string; //执行第一次类型兼容性检查,并返回结果
    if (s != null) 
        MessageBox.Show("转换成功!");
    else
        MessageBox.Show("转换失败!");

注:as比is少执行一次兼容性检查,性能可能会高一点点。



2、 c#字符串数组去掉空格

            //使用lambda表达式过滤掉空字符串
            lays = lays.Where(s => !string.IsNullOrEmpty(s)).ToArray();

3、string uploadFile = uploadFileName[i].Substring(uploadFileName[i].LastIndexOf("\\") + 1);  获取文件名

string currentPath = uploadFileName[i].Substring(0, uploadFileName[i].LastIndexOf("\\") + 1);  获取路径

string strExt = dlgOpen.FileNames[i].Substring(dlgOpen.FileNames[i].LastIndexOf(".") + 1);