System.ComponentModel.ReferenceConverter.ConvertFrom C# (CSharp) Method

ConvertFrom() public method

Converts the given object to the reference type.

public ConvertFrom ( ITypeDescriptorContext context, CultureInfo culture, object value ) : object
context ITypeDescriptorContext
culture System.Globalization.CultureInfo
value object
return object
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                string text = ((string)value).Trim();

                if (!String.Equals(text, s_none) && context != null)
                {
                    // Try the reference service first.
                    //
                    IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService));
                    if (refSvc != null)
                    {
                        object obj = refSvc.GetReference(text);
                        if (obj != null)
                        {
                            return obj;
                        }
                    }

                    // Now try IContainer
                    //
                    IContainer cont = context.Container;
                    if (cont != null)
                    {
                        object obj = cont.Components[text];
                        if (obj != null)
                        {
                            return obj;
                        }
                    }
                }
                return null;
            }
            return base.ConvertFrom(context, culture, value);
        }

Usage Example

Example #1
0
		public void ConvertFrom ()
		{
			ReferenceConverter converter = new ReferenceConverter (typeof(ITestInterface));
			string referenceName = "reference name";
			// no context
			Assert.IsNull (converter.ConvertFrom (null, null, referenceName), "#1");

			TestComponent component = new TestComponent();

			// context with IReferenceService
			TestReferenceService referenceService = new TestReferenceService ();
			referenceService.AddReference (referenceName, component);
			TestTypeDescriptorContext context = new TestTypeDescriptorContext (referenceService);
			Assert.AreSame (component, converter.ConvertFrom (context, null, referenceName), "#2");
			
			// context with Component without IReferenceService
			Container container = new Container ();
			container.Add (component, referenceName);
			context = new TestTypeDescriptorContext ();
			context.Container = container;
			Assert.AreSame (component, converter.ConvertFrom (context, null, referenceName), "#3");
		}