其他分享
首页 > 其他分享> > 约束参数,new()

约束参数,new()

作者:互联网

有什么方法可以将Parse方法移到抽象类中?我尝试了多种方法(底部的链接),但仍然遇到一个障碍.

public class AnimalEntityId : EntityId<AnimalEntityId>
{
    public AnimalEntityId()
        : base()
    {
    }

    private AnimalEntityId(string value)
        : base(value)
    {
    }

    public static AnimalEntityId Parse(string value)
    {
        return new AnimalEntityId(value);
    }
}


public abstract class EntityId<TEntityId>
{
    private readonly System.Guid value;

    protected EntityId(string value)
    {
        this.value = System.Guid.Parse(value);
    }

    protected EntityId()
    {
        this.value = System.Guid.NewGuid();
    }
}

尝试这些建议没有运气:

> Passing arguments to C# generic new() of templated type
> Is there a generic constructor with parameter constraint in C#?
> https://social.msdn.microsoft.com/Forums/en-US/fd43d184-0503-4d4a-850c-999ca58e1444/creating-generic-t-with-new-constraint-that-has-parameters?forum=csharplanguage
> http://www.gamedev.net/topic/577668-c-new-constraint–is-it-possible-to-add-parameters/

提前致谢!

解决方法:

如果您不介意使用反射,则可以将Parse移入抽象类型,如下所示:

public static TEntityId Parse(string val) {
    var constr = typeof(TEntityId).GetConstructor(
        // Since the constructor is private, you need binding flags
        BindingFlags.Instance | BindingFlags.NonPublic
    ,   null
    ,   new[]{ typeof(string) }
    ,   null);
    if (constr == null) {
        throw new InvalidOperationException("No constructor");
    }
    return (TEntityId)constr.Invoke(new object[] {val});
}

Demo.

标签:oop,inheritance,abstract-class,generics,c
来源: https://codeday.me/bug/20191119/2032614.html