开发者

Handle any type in method

I have two classes.

public class Handler
{

delegate T ReturnDelegate();

    public T HandleReturnMethod(ReturnDelegate d)
    {
        DoSomething(); //some other stuff

        return d();
    }
} 


public partial class Test
{

    protected int Id
    {
        get
        {
            return new Handler().HandleReturnMethod(delegate()
            {
                int id = 1;
                return id; 
            });
        }
    }
}

I want 开发者_C百科to be able to handle any Type in the Handler class. But 'T' seems not to work, int cannot be converted to it. If there is a better approach or something is wrong here, please comment.


You need to create the delegate type and method to use generics. Personally, I would use a standard delegate for this:

public T HandleReturnMethod<T>(Func<T> d)
{
    DoSomething(); //some other stuff
    return d();
}

Given the above, your code should work:

protected int Id
{
    get
    {
        return new Handler().HandleReturnMethod(() =>
        {
            int id = 1;
            return id; 
        });
    }
}


The reason your code wasn't working is because int ( Int32 ) is a structure not an object which is the reason it cannot normally be nullable unless you declare it as int? num = null;

If I am not mistaken only an object can have a Type ( both an object and a Type are classes ) not a structure. All classes are based on the object class ( which is the reason a collection that isn't a generic ( i.e. Type t ) elements are objects.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=VS.100).aspx

http://msdn.microsoft.com/en-us/library/ah19swz4.aspx

http://msdn.microsoft.com/en-us/library/ah19swz4(v=VS.100).aspx

http://msdn.microsoft.com/en-us/library/system.int32.aspx

http://msdn.microsoft.com/en-us/library/system.type.aspx

http://msdn.microsoft.com/en-us/library/system.object.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜