开发者

How to convert entitybase type to entity type in C#

开发者 https://www.devze.com 2023-04-04 17:54 出处:网络
I tried code below in .NET 3.5 but got exception at line shown in comment: Cannot convert type \'TUnpaid\' to \'ClassLibrary1.Unpaid\'

I tried code below in .NET 3.5 but got exception at line shown in comment:

Cannot convert type 'TUnpaid' to 'ClassLibrary1.Unpaid'

How to fix this in .NET 3.5 ?

namespace ClassLibrary1
{
    public class EntityBase
    {
        public virtual void Save<T>(T dok) where T : EntityBase, new()
        {
        }
    }

    public class Unpaid : EntityBase
   开发者_Python百科 {
        public override void Save<TUnpaid>(TUnpaid dok)
        {
            // Cannot convert type 'TUnpaid' to 'ClassLibrary1.Unpaid'  
            var kup = (Unpaid)dok;
        }
    }
}


If you make your EntityBase class generic, I think you can solve this problem:

public class EntityBase<T>
{
    public virtual void Save<T>(T dok) where T : EntityBase<T>, new()
    {
    }
}

public class Unpaid : EntityBase<Unpaid>
{
    public override void Save<Unpaid>(Unpaid dok)
    {
        // dok is now of type Unpaid and doesn't need the cast
    }
}


You either should write an operator of type conversion, or write a method (or class) which establishes the connections between two types.

In your code sample you use the two different types (TUnpaid and Unpaid) with no connection between them.

0

精彩评论

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