扩展Int以实现c#中的接口

时间:2012-06-19 20:25:53

标签: c#

是否可以在C#中(我认为不是)扩展int来实现接口(不创建包装类)?

我有一个像这样的界面

public interface IActionLoggerObject
{
    string GetForLogging();
}

我想(从概念上)能够做到这一点:

public class int:IActionLoggerObject
{
    string IActionLoggerObject.GetForLogging() { return "s"; }
}

3 个答案:

答案 0 :(得分:8)

  

是否有可能(我认为不是)(在c#中)扩展“int”来实现接口(不创建包装类)?

没有。您永远不能更改现有类型实现的接口。

目前尚不清楚为什么要这样做,但创建包装类几乎肯定是前进的方向。

答案 1 :(得分:3)

正如MNGwinn在他对Jon Skeet的回答中所提到的那样,如果满足您的所有要求,您可以使用扩展方法。

所以,像这样:

public static class ExtensionMethods
{
    public static string GetForLogging(this int @this)
    {
        return "s"; // or maybe return @this.ToString();
    }
}

让你这样做。

string val = 3.GetForLogging();

答案 2 :(得分:0)

另一种扩展方法可能性:

Console.WriteLine(32.AsActionLoggerObject().GetForLogging());
LoggingMethod(32.AsActionLoggerObject());

用法:

declare @Fields table (
ID int identity not NULL,
Name varchar(200)
)

declare @Tables table (
ID int identity not NULL,
Field varchar(200),
TempTable varchar(200)
)

declare @QueryTables table (
ID int identity not NULL,
[Table] varchar(200),
Alias varchar(20)
)

declare @QueryJoins table (
ID int identity not NULL,
Table1 varchar(20),
Col1 varchar(200),
Table2 varchar(20),
Col2 varchar(200)
)

insert @Fields
values
('W'),
('Y'),
('Z')

insert @Tables
values
('W', '#W'),
('WD', '#WD'),
('WE', '#WE'),
('WSF', '#WSF'),
('WSFE', '#WSFE'),
('XDF', '#XDF'),
('XDFE', '#XDFE'),
('Y', '#Y'),
('YD', '#YD'),
('Z', '#Z'),
('ZD', '#ZD')

insert @QueryTables
values
('#W', 'w'),
('#WD', 'wd'),
('#WE', 'we'),
('#WSF', 'wsf'),
('#WSFE', 'wsfe'),
('#XDF', 'xdf'),
('#XDFE', 'xdfe'),
('#Y', 'y'),
('#YD', 'yd'),
('#Z', 'z'),
('#ZD', 'zd')

insert @QueryJoins
values
('w', 'WID', 'wd', 'WID'),
('w', 'WID', 'we', 'WID'),
('w', 'WID', 'wsf', 'WID'),
('w', 'WID', 'xdf', 'WID'),
('w', 'WID', 'y', 'WID'),
('wd', 'WID', 'w', 'WID'),
('we', 'WID', 'wd', 'WID'),
('wsf', 'WID', 'wd', 'WID'),
('wsf', 'WSFID', 'wsfe', 'WSFID'),
('wsfe', 'WSFID', 'wsf', 'WSFID'),
('wsf', 'WSFID', 'xdf', 'WSFID'),
('xdf', 'WID', 'w', 'WID'),
('xdf', 'WSFID', 'wsf', 'WSFID'),
('xdf', 'XDFID', 'xdfe', 'XDFID'),
('xdfe', 'XDFID', 'xdf', 'XDFID'),
('y', 'YID', 'yd', 'YID'),
('yd', 'YID', 'y', 'YID'),
('y', 'YID', 'z', 'YID'),
('z', 'ZID', 'zd', 'ZID'),
('zd', 'ZID', 'z', 'ZID')

;
with a as (
select
row_number() over (order by Name) as rn, Name, Field, TempTable, [Table], Alias 
from @Fields vf
join @Tables vt
on vt.Field = vf.Name
join @QueryTables vqt
on vqt.[Table] = vt.TempTable )

select 'select * from ' + stuff((
select 
concat(
    case when a.rn =1 then a.TempTable else '' end, 
    ' ',
    case when a.rn =1 then a.Alias else '' end,
    ' join ', 
    a2.TempTable,
    ' ' , 
    a2.alias,
     ' on ', 
     q.Table1, 
     '.', 
     q.Col1, 
     ' = ', 
     q.Table2 , 
     '.', 
     q.Col2 ) from a
left join a a2
on a.name < a2.name
inner join @QueryJoins  q
on q.Table1 = a.alias 
and q.Table2 = a2.alias
for xml path('')), 1, 1, '')