[英]Call 3rd-party assembly's overloaded method from generic method using dynamic (or by other means)?
更新:事實證明,在查看所使用的庫的源代碼之前,我已經完全錯過了細節。 不好的示例代碼開始的道歉,是在試圖專注於我認為相關的內容。
使用FlatFiles NuGet庫,該庫的Property(...)
方法有25個重載。 我正在嘗試通過對要傳遞的參數使用dynamic來從通用方法中調度正確的Property(...)
重載,但這無法正常工作。 這是我嘗試過的:
using FlatFiles;
using FlatFiles.TypeMapping;
public class FixedWidthDataSource<FixedWidthRecordT> {
public IFixedLengthTypeMapper<FixedWidthRecordT> Mapper
= FixedLengthTypeMapper.Define<FixedWidthRecordT>()
;
...
public void MapProperty<T>(
Expression<Func<FixedWidthRecordT, T>> col
, int width
, string inputFormat = null
) {
var window = new Window(width);
Mapper.Property((dynamic)col, window);
}
}
public class FixedWidthRecord
{
public string First { get; set; }
public string Last { get; set; }
}
//later
var fwds = new FixedWidthDataSource<FixedWidthRecord>();
fwds.MapProperty(c=>c.First, 5);
一些屬性重載:
Property(Expression<Func<FixedWidthRecordT, bool>> property, Window window);
Property(Expression<Func<FixedWidthRecordT, int>> property, Window window);
Property(Expression<Func<FixedWidthRecordT, string>> property, Window window);
我得到的錯誤是'FlatFiles.TypeMapping.IFixedLengthTypeMapper<FixedWidthRecord>' does not contain a definition for 'Property'
。
查看源代碼,我看到有一個internal sealed class FixedLengthTypeMapper<TEntity>
,這是從對FixedLengthTypeMapper.Define<FixedWidthRecordT>()
的調用返回並分配給Mapper
的對象的類型。 但是, IFixedLengthTypeMapper
沒有Property(...)
任何定義,只有FixedLengthTypeMapper
擁有它們。
希望這一切都是相關的。
也許您的情況與此有關? RuntimeBinderException –“不包含”的定義 。
在匿名對象的情況下,該文章將獲得該例外,但您的情況似乎很相似。 您的程序集試圖通過dynamic
方式訪問它通常看不到的東西:您的情況下為internal
類,而internal
類為匿名類型。
在庫中添加[assembly: InternalsVisibleTo("Your.Assembly")]
屬性聽起來不是一個好選擇,但是如果您可以從源代碼構建它可能會暫時提供幫助。 或者,也許您可以利用該信息來創建可靠的副本。
盡管它是通過使用庫的使用文檔中未描述的接口,但我最終還是要使其正常工作。 我仍然很好奇如何解決此問題(例如,如果我在解決方案中使用的IFixedLengthTypeConfiguration接口也定義為內部)。
using FlatFiles;
using FlatFiles.TypeMapping;
public class FixedWidthDataSource<FixedWidthRecordT> {
public IFixedLengthTypeConfiguration<FixedWidthRecordT> Configuration
= FixedLengthTypeMapper.Define<FixedWidthRecordT>()
;
public IFixedLengthTypeMapper<FixedWidthRecordT> Mapper;
public FixedWidthDataSource() {
Mapper = (IFixedLengthTypeMapper<FixedWidthRecordT>)Configuration;
}
...
public void MapProperty<T>(
Expression<Func<FixedWidthRecordT, T>> col
, int width
, string inputFormat = null
) {
var window = new Window(width);
Configuration.Property((dynamic)col, window);
}
}
public class FixedWidthRecord
{
public string First { get; set; }
public string Last { get; set; }
}
//later
var fwds = new FixedWidthDataSource<FixedWidthRecord>();
fwds.MapProperty(c=>c.First, 5);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.