接口不包含属性的定义

时间:2015-07-10 07:33:45

标签: c# asp.net asp.net-mvc-5

首先,我不是一位经验丰富的.net开发人员,所以如果这个问题很疯狂,请原谅我。

我创建了一堆实现我的界面IEntity的模型。我想要接口所做的就是(现在)是为了确保这些模型包含一个Created属性来存储日期。

我想忽略为每个实例添加一个Created值,并让一些常用代码处理它,这就是我遇到问题的地方。

以下代码会产生构建错误:

public class Service<IEntity>
{
    // other code omitted 
    public virtual void Insert(IEntity entity)
    {
        entity.Created = DateTime.Now;

        // other code omitted
    }
}
  

错误15'IEntity'不包含'Created'和no的定义   扩展方法'Created'接受类型的第一个参数   可以找到“IEntity”(你是否错过了使用指令或者   装配参考?)

但这是我对IEntity的定义,当然IEntity的实现总是有一个Created属性。

public interface IEntity
{
    DateTime Created { get; set; }
}

那么有没有办法做我想做的事情,或者我应该忘记尝试以这种方式处理Created?

3 个答案:

答案 0 :(得分:1)

如果您将光标放在IEntity方法的Insert参数类型中并按 F12 ,它将转到IEntity的定义。

确保它是您粘贴的那个,并且在某个不同的命名空间中没有不同的IEntity导致混淆。

我已经嘲笑了你的例子,它对我来说很好。

以下编译和测试通过。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Tests
{
    public interface IEntity
    {
        DateTime Created { get; set; }
    }

    public class MyClass : IEntity
    {
        public DateTime Created { get; set; }
    }

    [TestClass]
    public class UnitTest1
    {
        private readonly DateTime _exampleDate;

        public UnitTest1()
        {
            _exampleDate = DateTime.Now;
        }

        public virtual void Insert(IEntity entity)
        {
            entity.Created = _exampleDate;
            // other code ommitted
        }

        [TestMethod]
        public void TestMethod1()
        {
            MyClass myTest = new MyClass();
            Insert(myTest);

            Assert.AreEqual(_exampleDate, myTest.Created);
        }
    }
}

答案 1 :(得分:1)

我发现适合的解决方案是使用约束。所以代码变成了这个:

public class Service<TEntity> where TEntity : IEntity
{
    // other code omitted 
    public virtual void Insert(TEntity entity)
    {
        entity.Created = DateTime.Now;

        // other code omitted
    }
}

https://msdn.microsoft.com/en-us/library/d5x73970.aspx

这允许我将这个类与我提到的任何“实现我的界面IEntity的模型”一起使用。

答案 2 :(得分:0)

你确定,你没有在方法中使用另一个IEntity吗?检查您的使用陈述。 似乎与“Created”存在命名冲突,因为它的颜色很奇怪。