简体   繁体   English

C#.NET动态自定义控件,动态返回类型

[英]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. 我创建了一个自usercontrol类继承的自定义控件。 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. 因此,我必须创建自己的Value属性。 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. 由于C#中的所有内容都隐式地继承自System.Object (甚至是值类型),因此您可以使其返回并将其强制转换为所需的类型。 The is operator can be used to check the type. is运算符可用于检查类型。

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

Alternatively, C# has a dynamic keyword which can be used to hold any type. 另外,C#具有一个dynamic关键字,可用于保存任何类型。

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. 这使您可以使用运算符和调用实例成员,而无需检查类型和类型转换,但是请注意,框架在运行时通过反射来解决dynamic问题,这意味着在编译时不会捕获任何错误,并且最终会导致异常。 。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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