简体   繁体   中英

c# .NET dynamic custom control, dynamic return type

Here's what i want to achieve:

We have created our own entityframework, and we pass our entity object onto a custom control. Based on the type (string, boolean, ...) and the rights we want out control to be created on the page different.

For instance:

type=string, access=read => display as label

type=string, access=edit => display as textbox

type=boolean, access=read => display as disabled checkbox

type=boolean, access=edit => display as enabled checkbox

We might add more later but we'll start with these.

I have created a custom control that inherits from the usercontrol class. The control is rendered on the page perfectly, this part i can manager.

The problem however is getting the data from it. Control does not have a text or checked property. So i have to create a Value property of my own. What i want this property to do is return a Boolean when it's a checkbox, and return Text when it's a label or a textbox. Is this possible at all and if so how do i do it? (i heard something about reflection, but i'm unsure how to give one getter multiple return type possibilities)

Since everything in C# implicitly inherits from System.Object (even value types), you can make that the return and cast it to the required type later. The is operator can be used to check the type.

object obj = "foo";
bool isString = obj is string; //true

Alternatively, C# has a dynamic keyword which can be used to hold any type.

class Foo
{
    public dynamic Value { get; private set; }

    public Foo( string value )
    {
        this.Value = value;
    }

    public Foo( bool value )
    {
        this.Value = value;
    }
}

This allows you to use operators and call instance members without checking types and casting, but beware, dynamic is resolved by the framework via reflection at runtime, which means any errors won't be caught at compile time and you'll end up getting exceptions.

The following compiles just fine, but will throw at runtime.

Foo BooleanFoo = new Foo( true );
Foo StringFoo  = new Foo( "StackOverflow" );

if( BooleanFoo.Value ) //returns true
    ...

if( StringFoo.Value ) //throws an exception
    ...

StringFoo.Value.Substring( 0, 5 ); //returns 'Stack'
BooleanFoo.Value.Substring( 0, 5 ); //throws an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM