C#中的通用类型和字段访问

时间:2019-07-17 06:52:40

标签: c# mongodb

如果我使用类名(例如sampleclass),则此代码可以正常工作,而不是T(类型), 但是如果我使用T,则表明

  

'T'不包含'TimeStamp'的定义并且无法访问   扩展方法'TimeStamp'接受类型为'T'的第一个参数   可以找到(您是否缺少using指令或程序集   参考?)

//Get collection.
var collection = this.GetDatabaseConnection().GetCollection<T>
    (collectionName);
//filter to read specific data.
var filter = Builders<T>.Filter.Where(result => result.TimeStamp >=
    startTime && result.TimeStamp <= endTime);
List < T > queryData = collection.Find<T>(filter, null).ToList();

以前是这样,并且运行良好:

//Get collection.
var collection = this.GetDatabaseConnection().GetCollection<Sampleclass>.
    (collectionName);
//filter to read data using specific timestamp.
var filter = Builders<Sampleclass>.Filter.Where(result =>
    result.TimeStamp >=
    startTime && result.TimeStamp <= endTime);
List < Sampleclass > queryData = collection.Find<Sampleclass>
    (filter, null).ToList();

3 个答案:

答案 0 :(得分:0)

问题在于T不具有TimeStamp属性,因为它是通用类型。如果始终需要访问集合中处理的任何类型的TimeStamp,则可以考虑使用具有TimeStamp作为get函数的接口。您要处理的所有类型都必须实现该接口。

public interface MyInterface 
{
    TimeSpan TimeStamp { get; } //or whatever type your are using for your TimeStamp property
}


var collection = this.GetDatabaseConnection().GetCollection<MyInterface> 
    (collectionName);
var filter = Builders<MyInterface>.Filter.Where(result => result.TimeStamp >= 
    startTime && result.TimeStamp <= endTime);
List<MyInterface> queryData = collection.Find<MyInterface>(filter,null).ToList();

这样,它仍然非常通用。如果您仍要使用类型T,则必须使用反射来查找已处理类型的属性TimeStamp

编辑:使用类型T的一些建议:您始终必须考虑T可以是任何东西,从整数到可以想象的任何其他对象。有时候,如果您有一个方法不需要访问类型T对象上给出的但用于许多不同类型的属性,则它可能非常有用。我最近使用T构建了一个小的ParseOrDefault方法来捕获无法转换的值:

private T ParseOrDefault<T>(Object value, T defaultValue)
{
    try
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }
    catch (Exception)
    {
        return defaultValue;
    }
}

一旦您不得不处理更具体的用例,T通常就没那么有用了。

答案 1 :(得分:0)

我会使用这样的基类

来做到这一点
<div class="container">
    -
    <div class="amount">
        $3
    </div>
</div>

答案 2 :(得分:0)

在阅读您对第一个答案的评论后,我想使用MongoDB.Entities提出以下解决方案

希望这或多或少是您想要实现的目标...

using MongoDB.Entities;
using System;
using System.Collections.Generic;

namespace StackOverflow
{
    public class Program
    {
        public class MySample : Entity
        {
            public DateTime TimeStamp { get; set; }
        }

        public class Sample1 : MySample
        {
            public string SomeProp { get; set; }
        }

        public class Sample2 : MySample
        {
            public string AnotherProp { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test");

            var sample1 = new Sample1 { SomeProp = "some prop value", TimeStamp = DateTime.UtcNow };
            var sample2 = new Sample2 { AnotherProp = "another prop", TimeStamp = DateTime.UtcNow };

            DB.Save(sample1);
            DB.Save(sample2);

            var s1 = FindSamples<Sample1>();
            var s2 = FindSamples<Sample2>();

            List<T> FindSamples<T>() where T : MySample
            {
                return DB.Find<T>()
                         .Many(s =>
                               s.TimeStamp >= DateTime.UtcNow.AddMinutes(-1) &&
                               s.TimeStamp <= DateTime.UtcNow.AddMinutes(1));
            }
        }
    }
}