C#中Scope属性如何使用

发布时间:2021-07-08 15:35:31 作者:Leah
来源:亿速云 阅读:460

本篇文章为大家展示了C#中Scope属性如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

Scope属性在C#中的应用的思路:

我们给控件添加一个复杂的类型Scope,并且给它的类型提供的一个类型转换器,现在我们可以在属性浏览器中编辑它的值,并且它的值也被串行化的源代码里了。但是你有没有发现,在属性浏览器里编辑这个属性的值还是不太方便。因为属性只是“10,200”这种形式的,所以,你必须按照这种格式来修改,一旦格式错误就会引发异常,比如输入一个“10200”。我们期望这个属性的每一子属性都能够被独立的编辑就好了,这并非不能实现,而且实现还很简单。

为了在属性浏览器里能够独立的编辑子属性,我们还要重写两个方法:GetPropertiesSupported()和GetProperties();下面是ScopeConverter的完整代码:

Scope属性在C#中的应用实例代码:

public class ScopeConverter : TypeConverter  {  public override bool CanConvertFrom(  ITypeDescriptorContext context, Type sourceType)  {  if (sourceType == typeof(String)) return true;   return base.CanConvertFrom(context, sourceType);  }   public override bool CanConvertTo(  ITypeDescriptorContext context, Type destinationType)  {  if (destinationType == typeof(String)) return true;   if (destinationType ==   typeof(InstanceDescriptor)) return true;   return base.CanConvertTo(context, destinationType);  }   public override object ConvertTo(  ITypeDescriptorContext context,   System.Globalization.CultureInfo culture,   object value, Type destinationType)  {  String result = "";  if (destinationType == typeof(String))  {  Scope scope = (Scope)value;  result = scope.Min.ToString()+"," + scope.Max.ToString();  return result;  ///Scope属性在C#中的应用  }   if (destinationType == typeof(InstanceDescriptor))  {  ConstructorInfo ci = typeof(Scope).GetConstructor(  new Type[] {typeof(Int32),typeof(Int32) });  Scope scope = (Scope)value;  return new InstanceDescriptor(ci,   new object[] { scope.Min,scope.Max });  }  return base.ConvertTo(context,   culture, value, destinationType);  }   public override object ConvertFrom(  ITypeDescriptorContext context,   System.Globalization.CultureInfo culture, object value)  {  if (value is string)  {  String[] v = ((String)value).Split(',');  if (v.GetLength(0) != 2)  {  throw new ArgumentException("Invalid parameter format");  }   Scope csf = new Scope();  csf.Min = Convert.ToInt32(v[0]);  csf.Max = Convert.ToInt32(v[1]);  return csf;  }  return base.ConvertFrom(context, culture, value);  }   public override bool GetPropertiesSupported(  ITypeDescriptorContext context)  {  return true;  }  ///Scope属性在C#中的应用  public override PropertyDescriptorCollection   GetProperties(ITypeDescriptorContext context,   object value, Attribute[] attributes)  {  return TypeDescriptor.GetProperties(  typeof(Scope), attributes);  }  }

在GetProperties方法里,我用TypeDescriptor获得了Scope类的所有的属性描述器并返回。如果你对TypeDescriptor还不熟悉的话,可以参考MSDN。重写这两个方法并编译以后,在测试工程里查看控件的属性,你可以看到Scope是如下的形式:

C#中Scope属性如何使用

上述内容就是C#中Scope属性如何使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. vue template中slot-scope/scope怎么用
  2. Angular中scope作用域如何使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

scope

上一篇:C#中有哪些引用类型

下一篇:C#中怎么利用Specification模式定制业务逻辑

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》