है, मेरे पास निम्न सी # कोड है जो मुझे पसंद नहीं है।जेनेरिक टाइप पैरामीटर जो कि आईनेमेरेबल <T>
आवश्यकता कुछ भी है कि किसी भी IEnumerable<T>
लागू करता है का उपयोग करता है दूसरी विधि है कि "2"
प्रिंट है, लेकिन कुछ और पहली विधि है कि "1"
प्रिंट उपयोग करता है।
एक बेवकूफ प्रदर्शन नीचे है। ICollection<int>
, IList<int>
, List<int>
और int[]
सभी IEnumerable<T>
लागू लेकिन "1"
बजाय "2"
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Test
{
public class Program
{
public static void Main()
{
var parent = new Parent<Class>();
// OK: TProperty == int. Prints "1"
parent.Map(c => c.IntValue);
// OK: TProperty == int. Prints "2"
parent.Map(c => c.IEnumerableIntValue);
// Wrong: TProperty == ICollection<int>. Prints "1"
parent.Map(c => c.ICollectionIntValue);
// Wrong: TProperty == List<int>. Prints "1"
parent.Map(c => c.ListIntValue);
// Wrong: TProperty == int[]. Prints "1"
parent.Map(c => c.ArrayIntValue);
}
public class Class
{
public int IntValue { get; set; }
public IEnumerable<int> IEnumerableIntValue { get; set; }
public ICollection<int> ICollectionIntValue { get; set; }
public List<int> ListIntValue { get; set; }
public int[] ArrayIntValue { get; set; }
}
}
public class Parent<T>
{
public void Map<TProperty>(Expression<Func<T, TProperty>> expression)
{
Console.WriteLine("1");
}
public void Map<TProperty>(Expression<Func<T, IEnumerable<TProperty>>> expression)
{
Console.WriteLine("2");
}
}
}
मैं
public void Map<TEnumerable, TElement>(Expression<Func<T, TEnumerable>> expression) where TEnumerable : IEnumerable<TElement>
{
Console.WriteLine("2");
}
को परिभाषा को बदलने की कोशिश की है छपा है, लेकिन यह स्पष्ट प्रकार पैरामीटर का उपयोग करने, जो की आवश्यकता है अस्वीकार्य:
parent.Map<int[], int>(c => c.ArrayIntValue);
क्या किसी को संकलन समय पर सी # में इसे प्राप्त करने के बारे में कोई विचार है? किसी भी विचार की सराहना की जाती है। हो सकता है कि कॉन्ट्रैक्ट/कॉन्वर्सेंट प्रतिनिधि काम कर सकें? मैंने सी # कंपाइलर के साथ झगड़ा करने की कोशिश की है लेकिन कहीं भी नहीं मिला है।
बीटीडब्ल्यू: स्ट्रिंग लागू करता है IENumerable। आपकी उम्मीदों का उपयोग करके, सभी कॉलों को "2" प्रिंट करना चाहिए। –
अब यह एक दिलचस्प बात है कि मैंने @rind –
के बारे में सोचा नहीं है INumerable के लिए अलग विधि बनाने के बारे में: 'सार्वजनिक शून्य मानचित्र संख्यात्मक (अभिव्यक्ति >> अभिव्यक्ति)' –